13

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
firmo23
  • 7,490
  • 2
  • 38
  • 114

3 Answers3

17

We could use rapply

lapply(LIST2, rapply, f = c)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Nice one, keep forgetting about rapply. I think OP wants output as list of lists. – zx8754 Jan 25 '18 at 12:49
  • 2
    @zx8754 Thanks, then wrapping with `list` as you have done would be the way to go `lapply(LIST2, function(x) list(rapply(x, f = c)))` – akrun Jan 25 '18 at 12:54
  • 1
    nice - also preserved the structure of my data better than [this solution](https://stackoverflow.com/questions/42739419/r-convert-nested-list-into-a-one-level-list) Not sure though why my output list is still nested one level deep. But this is a small problem in comparison to my previous highly nested list with elements of unequal length – Simone Nov 03 '21 at 08:15
9

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

lapply(LIST2, function(i) list(unlist(i, recursive = TRUE)))
zx8754
  • 52,746
  • 12
  • 114
  • 209
4

this should do it for you:

LIST2 <- lapply(LIST2, unlist)
waskuf
  • 415
  • 2
  • 4