0

Exactly as it sounds. I want to take a matrix and for each row, sum every n columns. I do not want to use apply or any loop wrapper. It needs to be as fast as possible. For example, see the below

set.seed(1)
M = matrix(rpois(16,4),4,4)
n = 2

 M
     [,1] [,2] [,3] [,4]
[1,]    3    2    5    5
[2,]    3    7    1    3
[3,]    4    7    2    5
[4,]    7    5    2    4


output

     [,1] [,2] 
[1,]   5   10
[2,]   10   4
[3,]   11   7
[4,]   12   6
wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90
  • This question you refer to is poorly asked and many of the solutions are not speed based. I believe my question is in fact new and important in documentation for stackoverflow. – wolfsatthedoor Sep 24 '15 at 17:17
  • Regardless, the solution from the question the one you posted to REFERS to has a nice solution: sapply(split.default(mydf, 0:(length(mydf)-1) %/% 2), rowSums) – wolfsatthedoor Sep 24 '15 at 17:19
  • I should notice I am the author of the function, but perhaps `taRifx:::splitc(M, INDEX = rep(1:(ncol(M)/n), each = n), FUN = rowSums)`. – Roman Luštrik Sep 24 '15 at 17:21
  • 1
    For `n=2` a neat solution would be just `M[,c(T,F)] + M[,c(F,T)]` – David Arenburg Sep 24 '15 at 18:24

0 Answers0