这是一种非常简单的方法。
首先,一些示例数据:
set.seed(1)
x <- cbind(Plant = letters[1:5],
as.data.frame(matrix(rnorm(60), ncol = 12)))
x
# Plant V1 V2 V3 V4 V5 V6
# 1 a -0.6264538 -0.8204684 1.5117812 -0.04493361 0.91897737 -0.05612874
# 2 b 0.1836433 0.4874291 0.3898432 -0.01619026 0.78213630 -0.15579551
# 3 c -0.8356286 0.7383247 -0.6212406 0.94383621 0.07456498 -1.47075238
# 4 d 1.5952808 0.5757814 -2.2146999 0.82122120 -1.98935170 -0.47815006
# 5 e 0.3295078 -0.3053884 1.1249309 0.59390132 0.61982575 0.41794156
# V7 V8 V9 V10 V11 V12
# 1 1.35867955 -0.4149946 -0.1645236 -0.7074952 0.3981059 1.9803999
# 2 -0.10278773 -0.3942900 -0.2533617 0.3645820 -0.6120264 -0.3672215
# 3 0.38767161 -0.0593134 0.6969634 0.7685329 0.3411197 -1.0441346
# 4 -0.05380504 1.1000254 0.5566632 -0.1123462 -1.1293631 0.5697196
# 5 -1.37705956 0.7631757 -0.6887557 0.8811077 1.4330237 -0.1350546
其次,找出“组”列。用于gl
创建列组:
myBreaks <- gl(ceiling((ncol(x)-1)/5), 5)[1:(ncol(x)-1)]
我们可以利用 中的这些信息sapply
,我们可以方便地使用rowMeans
来获取您正在寻找的值。
cbind(x[1],
sapply(levels(myBreaks), function(y) {
rowMeans(x[-1][myBreaks == y])
}))
# Plant 1 2 3
# 1 a 0.18778055 0.0031074991 1.1892529
# 2 b 0.36537233 -0.1083305812 -0.4896239
# 3 c 0.05997134 0.0646204262 -0.3515075
# 4 d -0.24235365 0.2024774526 -0.2798217
# 5 e 0.47255547 -0.0007180433 0.6489845