Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten recursive list

Tags:

r

There are quite a few questions apparently on this topic, but I can't see any general solution proposed: I have a deeply recursive list and want to flatten it into a single list of all the non-list items contained.

For example, take this nested list:

d = list(
  list(
    list(
      iris[sample(1:150,3),],
      iris[sample(1:150,3),]
    ),
    list(
      list(
        iris[sample(1:150,3),],
        list(
          iris[sample(1:150,3),],
          iris[sample(1:150,3),]
        )
      )
    )
  )
)

And turn it into this:

list(iris[sample(1:150,3),],
     iris[sample(1:150,3),],
     iris[sample(1:150,3),],
     iris[sample(1:150,3),],
     iris[sample(1:150,3),])

I tried some of the following, based on other solutions:

purrr::flatten(d)
plyr::llply(d, unlist)
lapply(d, unlist, use.names=FALSE)

None achieve the desired outcome, which in the example is a single list length 5, all items being a data.frame. Any suggestions appreciated.

like image 894
geotheory Avatar asked Dec 02 '17 01:12

geotheory


1 Answers

rrapply in the rrapply package is a generalization of rapply that can flatten the nested list into a list of leaves. dfaslist=FALSE will cause data frames to be regarded as leaves rather than being recursed into.

library(rrapply)

rrapply(d, f = identity, dfaslist = FALSE, how = "flatten")
like image 196
G. Grothendieck Avatar answered Nov 04 '22 04:11

G. Grothendieck