Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 查找矩阵列子集的行和_R - Fatal编程技术网

R 查找矩阵列子集的行和

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,]

这是一个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,]    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)