简体   繁体   中英

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

提取柱, cbind的data.frames,并计算出该行是指:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM