R 查找矩阵列子集的行和
这是一个10 x 12的矩阵:R 查找矩阵列子集的行和,r,R,这是一个10 x 12的矩阵: mat您可以使用蛮力方法,指定apply中的每一列: t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12])))) 使用非随机数据和较短的输入矩阵更容易查看: > x <- matrix(1:36, 3,12) > x [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,]
mat您可以使用蛮力方法,指定apply
中的每一列:
t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12]))))
使用非随机数据和较短的输入矩阵更容易查看:
> x <- matrix(1:36, 3,12)
> x
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 1 4 7 10 13 16 19 22 25 28 31 34
[2,] 2 5 8 11 14 17 20 23 26 29 32 35
[3,] 3 6 9 12 15 18 21 24 27 30 33 36
> t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12]))))
[,1] [,2] [,3]
[1,] 22 70 118
[2,] 26 74 122
[3,] 30 78 126
OP描述的是R中的行和:
# using Matthew Lundberg's example data
x <- matrix(1:36, 3,12)
g = split(seq(ncol(x)), (seq(ncol(x)) - 1) %/% 4 )
sapply(g, function(cols) rowSums( x[, cols] ))
# 0 1 2
# [1,] 22 70 118
# [2,] 26 74 122
# [3,] 30 78 126
我们可以转换为array
,使用apply
和MARGIN=1
得到colSums
n <- 4
t(apply(array(mat, dim=c(nrow(mat), n, ncol(mat)/n)), 1, colSums))
包装器函数recast
可用于使其紧凑
recast(mat, Var1~(Var2-1)%/%4, id.var=NULL, sum)
美好的根据应用程序,OP应考虑将数据保持在数组中开始。
n <- 4
t(apply(array(mat, dim=c(nrow(mat), n, ncol(mat)/n)), 1, colSums))
library(reshape2)
acast(melt(mat), Var1~(Var2-1)%/%n, value.var='value', sum)
recast(mat, Var1~(Var2-1)%/%4, id.var=NULL, sum)