MItrajyoti
MItrajyoti

Reputation: 578

Sum of mutiple columns by row values in a single column of a matrix in R

I have a matrix like :

m <- matrix(c(1:32),ncol = 8)

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    5    9   13   17   21   25   29
[2,]    2    6   10   14   18   22   26   30
[3,]    3    7   11   15   19   23   27   31
[4,]    4    8   12   16   20   24   28   32

I want to sum up and combine multiple say, 3 columns eg. columns 1,2 and 3 and replace the value of column 1 by the the resulting vector.

      [,1] [,4] [,5] [,6] [,7] [,8]
[1,]    15   13   17   21   25   29
[2,]    18   14   18   22   26   30
[3,]    21   15   19   23   27   31
[4,]    24   16   20   24   28   32

My question is what is the best way to do this.

I have taken the sum and replaced the matrix with the vector.

X<-rowSums(m[,c(1,2,3)]); m[,1] <- X; m <- m[,-c(2,3)]

The columns are named in my case. Is there a better way to do this ?

Upvotes: 0

Views: 43

Answers (2)

steffchy
steffchy

Reputation: 11

You could also resort to using apply, which is bit lengthier than the rowSums() approach.

cbind(apply(m[,-c(4:ncol(m))], 1, function(x){sum(x,na.rm=T)} ), m[,c(4:ncol(m))])

#      [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   15   13   17   21   25   29
#[2,]   18   14   18   22   26   30
#[3,]   21   15   19   23   27   31
#[4,]   24   16   20   24   28   32

However, rowSums would undoubtedly be the computationally faster way to go.

Upvotes: 0

akrun
akrun

Reputation: 887851

We can use the numeric index of columns to subset and do the rowSums, then cbind with the columns that are not used in the rowSums

cbind(rowSums(m[,1:3]), m[, -(1:3)])
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   15   13   17   21   25   29
#[2,]   18   14   18   22   26   30
#[3,]   21   15   19   23   27   31
#[4,]   24   16   20   24   28   32

Upvotes: 2

Related Questions