Reputation: 1651
What is an efficient way to turn a list of elements into a list of lists with only one element in each list. See example data below:
#This vector (but with many more elements) I'd like to turn into a list of list with one element in each.
vector <- c("element1", "element2", "element3")
# It should look like this:
list_vector <- list("element1", "element2", "element3")
#This is old: and not really how I want it:
list_vector <- list(list("element1"), list("element1"), list("element1"))
Thanks in advance
Upvotes: 2
Views: 1240
Reputation: 39737
Using as.list
will be an efficient way to turn each element of a vector into a list.
As your list_vector is an unnamed list
you can use as.list
, lapply
or sapply
to turn each element of a vector into a list with only one element in each.
x <- as.list(vector)
y <- lapply(vector, identity)
z <- unname(sapply(vector,list))
Test for Equality:
identical(x, list_vector)
[1] TRUE
identical(y, list_vector)
[1] TRUE
identical(z, list_vector)
[1] TRUE
Benchmark
x <- c("element1", "element2", "element3")
bench::mark("as.list" = as.list(x)
, "lapply" = lapply(x, identity)
, "sapply" = unname(sapply(x, list)))
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
# <bch:expr> <bch:t> <bch:t> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm>
#1 as.list 1.19µs 1.76µs 493963. 0B 98.8 9998 2 20.2ms
#2 lapply 1.78µs 2.02µs 341163. 0B 0 10000 0 29.3ms
#3 sapply 9.6µs 10.94µs 81512. 0B 32.6 9996 4 122.6m```
Upvotes: 5
Reputation: 4358
you could use
lapply(vector,list)
Edit: for new desired output
sapply(vector,list)
Upvotes: 3