So I have taken a look at this question posted before which was used for summing every 2 values in each row in a matrix. Here is the link: sum specific columns among rows. I als
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.