You can do this with a brute-force approach, specifying each column within apply
:
t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12]))))
It's easier to see with non-random data, and a shorter matrix for input:
> 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
You can also split the vector with split
, and while this is more idiomatic for R and more flexible, it is not really more readable:
> t(apply(x, 1, function(y) sapply(split(y, ceiling(seq_along(y)/4)), sum)))
1 2 3
[1,] 22 70 118
[2,] 26 74 122
[3,] 30 78 126