Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unlist an arbitrary level in R nested list?

Tags:

dataframe

r

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]]))
like image 294
Antti Avatar asked May 25 '15 11:05

Antti


1 Answers

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)
like image 120
Colonel Beauvel Avatar answered Oct 11 '22 20:10

Colonel Beauvel