Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : Convert nested list into a one level list [duplicate]

Tags:

list

r

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.

like image 908
hans glick Avatar asked Mar 11 '17 19:03

hans glick


1 Answers

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.

like image 181
989 Avatar answered Dec 02 '22 03:12

989