Extract then row.bind data.frames from nested list

2019-08-04 06:32发布

问题:

I have a function that outputs a large matrix (Mat1) and a small dataframe (Smalldf1) I store them in a list called "Result". This function is run inside a loop so I create many versions of my "Result" list until my loop ends....each time I add them to a list called "FINAL".

At the end of my loop I end up with a List called FINAL, that has many smaller "Result" lists inside...each containing a small dataframe and a large Matrix.

I want to rbind all of the small dataframes together to form one larger dataframe and call it DF1 - I'm not sure how I access these now that I'm accessing a list within a list..?

A similar question on here gave a solution like this:

DF1 <- do.call("rbind",lapply(FINAL, function(x) x["Smalldf1"]))

However this gives the output as a single column called "Smalldf1" with the description of Smalldf1...ie this is literally printed in the column list(X1="xxx", X2="xxx", X3="xxx")...I need this broken out to look like the original format, 3 columns housing the information...?

Any help would be great.

回答1:

I make my comment into an answer. This could be your data:

df <- data.frame(X1=1:3, X2=4:6, X3=7:9)
FINAL=list(Result=list(Smalldf1=df, Mat1=as.matrix(df)),
             Result=list(Smalldf1=df+1, Mat1=as.matrix(df+1)))

You can combine lapply to extract the first (or Nth, just change the 1) elements of the nested lists, and then do a rbind on this result, either with do.call or with dplyr:

#### # Doing it in base R:
do.call("rbind", lapply(FINAL, "[[", 1) )
#### # Or doing it with dplyr:
library(dplyr)
lapply(FINAL, "[[", 1) %>% bind_rows
####   X1 X2 X3
#### 1  1  4  7
#### 2  2  5  8
#### 3  3  6  9
#### 4  2  5  8
#### 5  3  6  9
#### 6  4  7 10

This should be your expected result

WARNING: The solution using dplyr doesn't work for old versions of dplyr (i tested it on dplyr_0.5.0, but it returns an error on dplyr_0.2 for instance)