2

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.

agenis
  • 8,069
  • 5
  • 53
  • 102
PaulBeales
  • 475
  • 1
  • 8
  • 21
  • Please provide some example data using dput() – tobiasegli_te Oct 17 '16 at 09:28
  • getting an error - Error in lapply() RHS appears to be a function name , but it cannot be found – PaulBeales Oct 17 '16 at 09:34
  • Yes - this is what my data looks like..running your solution on this data i get this error: Error: cannot convert object to a data frame. – PaulBeales Oct 17 '16 at 09:42
  • OK - it works on the 2nd element...it seems to work on your example just fine but for some reason i get an error on my code "RHS appears to be a function name, but it cannot be found"...I'm sorry I know you don't have my code, I can't share the output. – PaulBeales Oct 17 '16 at 09:48
  • Please modify your question to include the result of this: `str(head(FINAL, 2))` – agenis Oct 17 '16 at 09:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125894/discussion-between-paulbeales-and-agenis). – PaulBeales Oct 17 '16 at 09:56

1 Answers1

2

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)

agenis
  • 8,069
  • 5
  • 53
  • 102