4
df1 <- data.frame(Profit=c(7,2,8), CSR=c(1, 5, 9), row.names = c("A", "B", "C"))
df2 <- data.frame(Profit=c(13,4,2), CSR=c(4, 2, 8), row.names = c("A", "B", "C"))
df3 <- data.frame(Profit=c(6,2,5), CSR=c(3, 8, 20), row.names = c("A", "B", "C"))
l<-list(df1, df2, df3)
l
dfmean<- data.frame(Profit=c(9,3,5), CSR=c(2, 6, 13), row.names = c("A", "B", "C"))
dfmean

I want to call a function (here: mean) on all three (or more) data frames stored in a list, returning those data frames combined in one single data frame. In this case it should look like dfmean.

1
  • Do all data.frames have the same number of rows? And what you want is the mean of the elements in row 1, the mean of the elements in row 2 etc? Is it a one-off or are you looking for a more generic solution?
    – vaettchen
    Jun 27, 2015 at 4:55

2 Answers 2

7

You can add them all up with Reduce("+", l) and then divide that sum by the total number of data frames.

Reduce("+", l) / length(l)
#     Profit       CSR
# A 8.666667  2.666667
# B 2.666667  5.000000
# C 5.000000 12.333333
1
  • Super interesting use of those functional programming concepts (which honestly I didn't even know were implemented in base R). I fully expected to see someone come at this with a dplyr solution, and you might have held that gem in reserve to make them feel bad for doubting base R. ;) Very nice! Jun 27, 2015 at 6:25
1

In a large dataset, I would suspect some missing values (NA). In that case, you could use mean with na.rm=TRUE after converting to array

 apply(array(unlist(l), c(3,2,3)),c(1,2), mean, na.rm=TRUE)
 #        [,1]      [,2]
 #[1,] 8.666667  2.666667
 #[2,] 2.666667  5.000000
 #[3,] 5.000000 12.333333

Or use rowMeans

 apply(array(unlist(l), c(3, 2, 3)), 2, rowMeans, na.rm=TRUE)
 #      [,1]      [,2]
 #[1,] 8.666667  2.666667
 #[2,] 2.666667  5.000000
 #[3,] 5.000000 12.333333

Or using dplyr/tidyr, we unnest the list ('l'), create a grouping variable 'n', and use summarise_each

 library(dplyr)
 library(tidyr)
 unnest(l, gr) %>% 
         group_by(gr) %>%  
         group_by(n=row_number())  %>%
         summarise_each(funs(mean(., na.rm=TRUE)), Profit:CSR)
 #  n   Profit       CSR
 #1 1 8.666667  2.666667
 #2 2 2.666667  5.000000
 #3 3 5.000000 12.333333

If there are no NAs, I think @josilber's solution is very compact and elegant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.