嵌套在列表

时间:2015-08-05 18:20:21

标签: r list dataframe

我有很多data.frames嵌套在列表中,并希望获得data.frames中列的行方式。这是我的MWE。我想知道如何在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

像这样的东西

(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

被修改

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

如何更加连贯地编写(ls1$df+ls2$df)/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

2 个答案:

答案 0 :(得分:2)

提取列cbind data.frames,并计算行意味着:

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

答案 1 :(得分:1)

如果没有NA值,则另一个选项是使用+进行元素明确(Reduce)并除以&{39} ls1&length #39;

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