hans glick hans glick - 9 months ago 34
R Question

R : Convert nested list into a one level list

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.

989 989
Answer Source

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.