Sum Every N Values in Matrix

心已入冬 提交于 2019-12-02 04:31:35

To sum consecutive sets of n elements from each row, you just need to write a function that does the summing and apply it to each row:

n <- 3
t(apply(y, 1, function(x) tapply(x, ceiling(seq_along(x)/n), sum)))
#       1  2  3
# [1,] 12 39 66
# [2,] 15 42 69
# [3,] 18 45 72

Transform the matrix to an array and use colSums (as suggested by @nongkrong):

y <- matrix(1:27, nrow = 3)
n <- 3

a <- y
dim(a) <- c(nrow(a), ncol(a)/n, n)
b <- aperm(a, c(2,1,3))
colSums(b)
#     [,1] [,2] [,3]
#[1,]   12   39   66
#[2,]   15   42   69
#[3,]   18   45   72

Of course this assumes that ncol(y) is divisible by n.

PS: You can of course avoid creating so many intermediate objects. They are there for didactic purposes.

I would do something similar to the OP -- apply rowSums on subsets of the matrix:

n  = 3
ng = ncol(y)/n
sapply( 1:ng, function(jg) rowSums(y[, (jg-1)*n + 1:n ]))

#      [,1] [,2] [,3]
# [1,]   12   39   66
# [2,]   15   42   69
# [3,]   18   45   72
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!