Summing rows of rolling columns

217 views Asked by At

I need to apply a rolling function that sums the rows of every two columns, so the rows of columns 1&2 will be summed, 3&4, etc.

m<-matrix(c(1,2,3,4,5,3,4,5,6,2,4,6,6,7,3,2,4,4,5,7),nrow=2,byrow=T)

I have looked at many functions including apply, rollapply, aggregate, etc. but cant seem to find one that roll sums the rows of specified columns.

I am more than capable of writing the code out the long way however am looking for an efficient solution which most likely involves a function.

sum1<-(m[,1]+m[,2])
sum2<-(m[,3]+m[,4])
sum3<-(m[,5]+m[,6])
sum4<-(m[,7]+m[,8])
sum5<-(m[,9]+m[,10])

cbind(sum1,sum2,sum3,sum4,sum5)   

Thanks!

3

There are 3 answers

0
Colonel Beauvel On

You can use this approach:

m[,seq(1, ncol(m),2)] + m[,seq(2, ncol(m), 2)]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    3    7    8    9    8
#[2,]   10   13    5    8   12
0
Neal Fultz On

You can use a matrix multiply:

> n <- ncol(m)/2
> S <- diag(n)[rep(1:n, each=2),]
> S
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    0    0    0    0
 [2,]    1    0    0    0    0
 [3,]    0    1    0    0    0
 [4,]    0    1    0    0    0
 [5,]    0    0    1    0    0
 [6,]    0    0    1    0    0
 [7,]    0    0    0    1    0
 [8,]    0    0    0    1    0
 [9,]    0    0    0    0    1
[10,]    0    0    0    0    1
> m %*% S
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    7    8    9    8
[2,]   10   13    5    8   12
0
Neal Fultz On

Another approach would be to convert m to a 3 dimensional array, then sum over the columns:

> X <- m
> dim(X) <- c(2,2,5)
> colSums(aperm(X, c(2,1,3)))
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    7    8    9    8
[2,]   10   13    5    8   12