rlist

Flatten nested lists in a list


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?


Solution

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

    lapply(LIST2, function(i) list(unlist(i, recursive = TRUE)))