简体   繁体   中英

Convert list to list of lists

How can I convert the list of strings a to list of lists b as

a = list('A', 'B', 'C')

and the converted to

b = list(list('A'), list('B'), list('C'))

Apply the function list to the list a :

lapply(a, list)
[[1]]
[[1]][[1]]
[1] "A"


[[2]]
[[2]][[1]]
[1] "B"


[[3]]
[[3]][[1]]
[1] "C"

A possible solution, using purrr::map :

library(tidyverse)

a = list('A', 'B', 'C')
b = list(list('A'), list('B'), list('C'))

a %>% map( ~ list(.x)) %>% identical(b)

#> [1] TRUE

a %>% map( ~ list(.x))

#> [[1]]
#> [[1]][[1]]
#> [1] "A"
#> 
#> 
#> [[2]]
#> [[2]][[1]]
#> [1] "B"
#> 
#> 
#> [[3]]
#> [[3]][[1]]
#> [1] "C"

Or simply:

map(a, list)

Another base R option:

Map(list, a)

Output

[[1]]
[[1]][[1]]
[1] "A"

[[2]]
[[2]][[1]]
[1] "B"

[[3]]
[[3]][[1]]
[1] "C"

Benchmark

As suspected, lapply is the fastest.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM