7

I got the following y nested list :

x1=c(12,54,2)
x2=c(2,88,1)
x3=c(4,8)

y=list()
y[[1]]=x1
y[[2]]=list(x2,x3)

y
[[1]]
[1] 12 54  2

[[2]]
[[2]][[1]]
[1]  2 88  1

[[2]][[2]]
[1] 4 8

I would like to extract all elements from this nested list and put them into a one level list, so my expected result should be :

y_one_level_list
[[1]]
[1] 12 54  2

[[2]]
[1]  2 88  1

[[3]]
[1] 4 8

Obviously ma real problem involve a deeper nested list, how would you solve it? I tried rapply but I failed.

hans glick
  • 2,431
  • 4
  • 25
  • 40

2 Answers2

18

Try lapply together with rapply:

lapply(rapply(y, enquote, how="unlist"), eval)

#[[1]]
#[1] 12 54  2

#[[2]]
#[1]  2 88  1

#[[3]]
#[1] 4 8

It does work for deeper lists either.

989
  • 12,579
  • 5
  • 31
  • 53
8

You can try this:

flatten <- function(lst) {
    do.call(c, lapply(lst, function(x) if(is.list(x)) flatten(x) else list(x)))
}

flatten(y)

#[[1]]
#[1] 12 54  2

#[[2]]
#[1]  2 88  1

#[[3]]
#[1] 4 8
Psidom
  • 209,562
  • 33
  • 339
  • 356