如何跨三个多列数据框的行计算均值? [英] How to calculate means across rows of three multi-column dataframes?

查看:16
本文介绍了如何跨三个多列数据框的行计算均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 3 个数据帧,每个数据帧都是一个 5x5 的对象:

Let's say I have 3 data frames, each a 5x5 object as such:

set.seed(1)
x <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(x) <-c("a","b","c","d","e")

y <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(y) <-c("f","g","h","i","j")

z <-as.data.frame(matrix(rnorm(10),ncol=5,nrow=5))
colnames(z) <-c("k","l","m","n","o")

例如,x 看起来像:

  > x
           a          b          c          d          e
1 -0.6264538 -0.8204684 -0.6264538 -0.8204684 -0.6264538
2  0.1836433  0.4874291  0.1836433  0.4874291  0.1836433
3 -0.8356286  0.7383247 -0.8356286  0.7383247 -0.8356286
4  1.5952808  0.5757814  1.5952808  0.5757814  1.5952808
5  0.3295078 -0.3053884  0.3295078 -0.3053884  0.3295078

如何有效地计算每个数据框中同一位置的 3 个值的跨行均值?也就是说,例如,计算数据帧上第 1 行/第 1 列中的 3 个值的平均值.当然,手动操作很容易.例如:

How can I efficiently calculate the means across rows for the 3 values in the same spot in each data frame? That is, calculate the mean for the 3 values in row 1/col 1 over the data frames, for instance. Easy to do manually, of course. For instance:

> mean(c(x$a[1],y$f[1],z$k[1]))
[1] 0.6014349

> mean(c(x$b[1],y$g[1],z$l[1]))
[1] -0.3071769

...等等.但是,对于更大的数据帧,我如何在 R 中有效地做到这一点?我试过 mapply() 和 apply() 和sweep() 的变体,但没有运气.我知道有一个简单的解决方案,但我脑子有问题.任何帮助将不胜感激!

... and so on. But how can I do this efficiently in R for much larger data frames? I've tried mapply() and variations on apply() and sweep(), but no luck. I know there's a simple solution but I'm having brain-lock. Any help would be greatly appreciated!

推荐答案

我觉得我必须提供我的琐碎解决方案作为答案...

I feel like I have to supply my trivial solution as an answer...

(x+y+z)/3

这篇关于如何跨三个多列数据框的行计算均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆