Sum adjacent columns for each column in a matrix of R

I am trying to get a function opposite to the diff () function. I want to add the values ​​of neighboring columns to the matrix for each column in the matrix. I don't need the sum of the whole column or row. For instance:

If I had:

[ 1  2  4;
  3  5  8 ]

I would finish:

[ 3  6;
  8  13 ]

Of course, for one or two columns it’s easy, because I can just do x [, 1] + x [, 2], but these matrices are pretty big.

I am surprised that I cannot find an effective way to do this.

+3
source share
3 answers
m <- matrix(c(1,3,2,5,4,8), nrow=2)
m[,-1] + m[,-ncol(m)]

     [,1] [,2]
[1,]    3    6
[2,]    8   13

Or just for fun:

n <- ncol(m)
x <- suppressWarnings(matrix(c(1, 1, rep(0, n-1)), 
                             nrow = n, ncol = n-1))
m %*% x

     [,1] [,2]
[1,]    3    6
[2,]    8   13
+4
source

Dummy data

mat <- matrix(sample(0:9, 100, replace = TRUE), nrow = 10)

Decision:

sum.mat <- lapply(1:(ncol(mat)-1), function(i) mat[,i] + mat[,i+1])
sum.mat <- matrix(unlist(sum.mat), byrow = FALSE, nrow = nrow(mat))
+2
source

:

m <- matrix(c(1,2,4,3,5,8), nrow=2, byrow=T)
sapply(2:ncol(m), function(x) m[,x] + m[,(x-1)])
0

All Articles