Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten nested lists in a list

Tags:

list

r

I have a list with nested lists inside.

LIST2 <- list(list("USA","WY","TX","AZ","Canada", "CA", "NY", 'Russia', 'NY'), 
             list(c("USA","Canada","CA","WY", 'China', 'AZ', 'AZ', 'AZ', 'WY')), 
             list(c("USA","Australia","CA","AR", 'AZ', 'WY', 'New Zealand', 'Japan', 'Japan', 'NJ')),
             list(list('Australia', 'Australia', 'Japan', 'Malaysia' )),
             list(c('USA', 'Australia', 'Japan', 'Malaysia' )))

I would like to flatten somehow the 1st and 4th list so they are same form as the rest of them. Is this possible?

like image 361
firmo23 Avatar asked Jan 25 '18 12:01

firmo23


2 Answers

We could use rapply

lapply(LIST2, rapply, f = c)
like image 95
akrun Avatar answered Oct 14 '22 23:10

akrun


Loop through the list, unlist recursively, then return as a list:

lapply(LIST2, function(i) list(unlist(i, recursive = TRUE)))
like image 39
zx8754 Avatar answered Oct 14 '22 23:10

zx8754