I have a nested list that has three levels. I need to unlist the middle level, but I have not found an easy way to do it.
E.g.
df1 <- data.frame(X = sample(100),
Y = sample(100))
df2 <- data.frame(X = sample(50),
Y = sample(50))
df3 <- data.frame(X = sample(150),
Y = sample(150),
Z = sample(150))
df4 <- data.frame(X = sample(20),
Y = sample(20),
Z = sample(20))
list1 <- list(A = df1, B = df2)
list2 <- list(A = df3, B = df4)
masterList <- list(list1, list2)
What I want to achieve is
newMasterList <- list(A = rbind(df1,df2), B = rbind(df3,df4))
I've tried unlist() with the both recursive options but they don't yield the desired result:
newMasterListFAIL1 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]], recursive = F))
newMasterListFAIL2 <- lapply(seq_along(masterList), function(x) unlist(masterList[[x]]))
You can try fast rbindlist
from data.table
package (but your list of data.frame
will be converted to a list of data.table
):
library(data.table)
newMasterList = lapply(masterList, rbindlist)
The base R solution from @akrun:
newMasterList = lapply(masterList, function(x) do.call(rbind, x))
And an elegant solution from @David Arenburg
library(tidyr)
newMasterList = lapply(masterList, unnest)
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