I need to append lists contained inside a top-level list. Other levels should be preserved, and there should be more than 2 elements possible.
l <- list(list(1:5), list(6:10))
required <- c(l[[1]], l[[2]])
I need to append lists contained inside a top-level list. Other levels should be preserved, and there should be more than 2 elements possible.
l <- list(list(1:5), list(6:10))
required <- c(l[[1]], l[[2]])
1) We can flatten with c from base R
do.call(c, l)
-output
#[[1]]
#[1] 1 2 3 4 5
#[[2]]
#[1] 6 7 8 9 10
2) Or with unlist with recursive = FALSE. Also a base R solution
unlist(l, recursive = FALSE)
3) Or with lapply (base R)
lapply(l, unlist, recursive = FALSE)
4) Or using Map (another base R)
Map(c, l)
5) Or with flatten from purrr
library(purrr)
flatten(l)
You can also use mapply():
#Code
mapply(c,l)
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
Or also lapply():
#Code 2
lapply(l,unlist)
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
Or sapply():
#Code 3
sapply(l,c)
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
All base R solutions.