Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : applying function on list of similar dataframes

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.

like image 886
suzukiav Avatar asked Feb 09 '23 17:02

suzukiav


1 Answers

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
like image 68
josliber Avatar answered Feb 12 '23 08:02

josliber