N个连续列的行平均值 [英] Rowmeans for N sequential columns
本文介绍了N个连续列的行平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在具有 n * 3
列的数据框中,如何为每三个(或任何其他数字)连续列计算行均值,例如对于列(1,2,3)
,(4,5,6)
, (7,8,9)
,等等?
In a dataframe with n*3
columns, how to calculate row means for every three (or any other number) sequential columns, e.g. for columns (1,2,3)
, (4,5,6)
, (7,8,9)
, etc?
有一个解决方案此处是代码审查-表示数据帧许多子集的平均值,但我想知道是否还有一种更优雅的方法。
There is a solution here on Code Review-Mean of many subsets of a dataframe, but I wonder if there is a more elegant method.
推荐答案
您可以使用以下内容。此示例基于链接的问题中提供的数据集以及每两个连续的列。
You can use the following. This example is based on the data-set provided in the linked question and for every two consecutive columns.
dat <- data.frame(a1 = 9:11, a2 = 2:4, b1 = 3:5,
b2 = 4:6, c1 = 5:7, c2 = 1:3)
n <- 2
t(rowsum(t(dat), as.integer(gl(ncol(dat), n, ncol(dat))))) / n
## 1 2 3
## [1,] 5.5 3.5 3
## [2,] 6.5 4.5 4
## [3,] 7.5 5.5 5
这篇关于N个连续列的行平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文