user2246905
user2246905

Reputation: 1039

Add columns of a matrix based on values of another vector

Suppose I have the following matrix:

 mat <- matrix(1:20, ncol=5)
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

and the following vector

counts=c(2,1,2)

I need to collapse this matrix by adding the columns based on each value of that vector counts. That means that the first two columns most be added, the third remain equal and sum the last two columns. My resulting matrix must be like this

      [,1] [,2] [,3] 
[1,]    6    9   30
[2,]    8   10   32
[3,]    10  11   34
[4,]    12  12   36

How could I do this in an automatic way, given that in my case I have a very big matrix and with a vector of counts with different values?

Upvotes: 2

Views: 126

Answers (2)

alexis_laz
alexis_laz

Reputation: 13122

Another idea, conceptually similar to akrun's:

t(rowsum(t(mat), rep(seq_along(counts), counts)))
#      1  2  3
#[1,]  6  9 30
#[2,]  8 10 32
#[3,] 10 11 34
#[4,] 12 12 36

Upvotes: 2

akrun
akrun

Reputation: 887048

One way would be to replicate the sequence of 'counts' by 'counts' vector, use that to split the column sequence of 'mat' to return a list, loop through the list with sapply, use the column index to subset the 'mat' for each list element and get the rowSums.

mat2 <- sapply(split(1:ncol(mat), rep(seq_along(counts), counts)), 
           function(i) rowSums(mat[,i,drop=FALSE]))
dimnames(mat2) <- NULL
mat2
#     [,1] [,2] [,3]
#[1,]    6    9   30
#[2,]    8   10   32
#[3,]   10   11   34
#[4,]   12   12   36

Upvotes: 3

Related Questions