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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With