MYaseen208
MYaseen208

Reputation: 23948

Mean of each row of data.frames column nested in list

I have many data.frames nested in a list and want to get the row means of a column in the data.frames. Here is my MWE. I am wondering how to accomplish this in R?

set.seed(12345)
df1 <- data.frame(x=rnorm(10))
df2 <- data.frame(x=rnorm(10))
ls1 <- list(df1=df1, df2=df2)
ls1

$df1
            x
1   0.5855288
2   0.7094660
3  -0.1093033
4  -0.4534972
5   0.6058875
6  -1.8179560
7   0.6300986
8  -0.2761841
9  -0.2841597
10 -0.9193220

$df2
            x
1  -0.1162478
2   1.8173120
3   0.3706279
4   0.5202165
5  -0.7505320
6   0.8168998
7  -0.8863575
8  -0.3315776
9   1.1207127
10  0.2987237

Something like this one

(ls1$df1+ls1$df2)/2


    x
1   0.23464051
2   1.26338903
3   0.13066227
4   0.03335964
5  -0.07232227
6  -0.50052806
7  -0.12812949
8  -0.30388085
9   0.41827645
10 -0.31029915

Edited

ls1 <- list(df=df1)
ls2 <- list(df=df2) 

How this (ls1$df+ls2$df)/2 can be written more coherently?

             x
1   0.23464051
2   1.26338903
3   0.13066227
4   0.03335964
5  -0.07232227
6  -0.50052806
7  -0.12812949
8  -0.30388085
9   0.41827645
10 -0.31029915

Upvotes: 0

Views: 763

Answers (2)

akrun
akrun

Reputation: 887991

If there are no NA values, another option would be to do element wise (+) with Reduce and divide by the length of 'ls1'

Reduce(`+`, ls1)/length(ls1)
#            x
#1   0.23464051
#2   1.26338903
#3   0.13066227
#4   0.03335964
#5  -0.07232227
#6  -0.50052806
#7  -0.12812949
#8  -0.30388085
#9   0.41827645
#10 -0.31029915

Upvotes: 1

Roland
Roland

Reputation: 132999

Extract the column, cbind the data.frames, and calculate the row means:

rowMeans(do.call(cbind, lapply(ls1, "[", "x")))

Upvotes: 2

Related Questions