Binding corresponding data frame elements of multiple lists in R (with gapply for function)

681 views Asked by At

I have a function that outputs a list of 3 data frames. As a toy example:

tfunction<-function(x){
d1a<-data.frame(a=1*x$variable[1],b=2*x$variable[1])
d1b<-data.frame(c=letters[x$variable[1]],d=3*x$variable[1])
d1c<-data.frame(e=4*x$variable[1],f=letters[x$variable[1]])
l1<-list(d1a,d1b,d1c)
return(l1)
}

I then want to apply that function across different groups in my dataset. Let's say in this toy example my data frame is:

df<-data.frame(variable=c(1,2,3),other=c(4,5,6))

My desired output is:

[[1]]  a   b
       1   2
       2   4
       3   6 
[[2]]  c   d
       a   3
       b   6
       c   9 
[[3]]  e   f
       4   a
       8   b
       12  c

Normally, when my function outputs a single data frame, I do this via:

library(nlme)    
do.call(rbind.data.frame, gapply(df, groups=df$variable, FUN=tfunction))

However, because my function output is a list of dataframes, rather than a single dataframe, this doesn't work. I know that I can merge two lists of dataframes by:

mapply(rbind, list1, list2)

However, I cannot figure out how to do this in conjunction with gapply. My attempt:

mapply(rbind, gapply(z, groups=z$variable, FUN=function))

resulted in all of the data frames being compiled into a single list. How can I get R to rbind each corresponding data frame into one final list of 3 dataframes? (Alternately, if anyone has a better approach than gapply to apply the function by group and then merge the data frames, I welcome that too!) Thanks for any help!

1

There are 1 answers

0
MPhD On BEST ANSWER

I got it to work! I'm sure there is a more elegant way to do this, but the following seems to do the job:

Reduce(function(x,y) Map(rbind, x, y),gapply(df, groups=df$variable, FUN=tfunction))