Mr K
Mr K

Reputation: 446

cumulative sum for rows upto select row number followed by summing up columns matrix in R

I am trying to perform following kind of summation on a matrix:

Let's say the matrix is:

    mat <- matrix(c(1:5,rep(0,7),c(1:7),rep(0,5),c(1:10), 0,0), 12,3)

I want to do cumulative sum on rows up to row numbers 5, 7, 10 for column numbers 1,2,3 respectively. (The real data can have arbitrary number of rows and columns).

For now, I have been using following code:

    sum1 <- matrix(rep(0, 36), 12, 3)
    row_index <- c(5,7,10)
    for (k in 1:3) {
      sum1[1:row_index[k], k] <- cumsum(mat[1:row_index[k], k])
    }
    sum1 <- matrix(apply(sum1,1,sum))

To start with, I have the matrix and row_index. I want to avoid using the loop as the data has a lot of columns. I am wondering if there is a way to do that.

Upvotes: 2

Views: 1114

Answers (2)

jeremycg
jeremycg

Reputation: 24945

First, define a function:

sumcolumn <- function(rows, columns, mat){
  cumsum(mat[1:rows, columns])
}

then use mapply on your vectors of columns/rows:

mapply(sumcolumn, rows = c(5, 7, 10), columns = c(1, 2, 3), MoreArgs = list(mat = mat))

Upvotes: 1

IRTFM
IRTFM

Reputation: 263481

depth <- c(5,7,10)
mapply( function(x,y) cumsum(mat[1:x, y]), depth, seq_along(depth) )

[[1]]
[1]  1  3  6 10 15

[[2]]
[1]  1  3  6 10 15 21 28

[[3]]
 [1]  1  3  6 10 15 21 28 36 45 55

Upvotes: 2

Related Questions