procerus
procerus

Reputation: 294

sum of specific columns in matrices

I have several matrices which have different values in first column and second column and same values in the third one, I would like to sum them and the result matrix to consist of first column and second column that is sum of matrices and no operation should be done with the third column.

a<-matrix(1:9,3,3)
b<-matrix(c(2:7,7,8,9),3,3)
c<-matrix(c(3:8,7,8,9),3,3)

result matrix:

d<-matrix(c(6,9,12,15,18,21,7,8,9),3,3)
d

Any idea on how I should proceed with this? I tagged dplyr because I think the answer might lie there, but base R answers are also more than welcome.

Upvotes: 0

Views: 345

Answers (1)

s_baldur
s_baldur

Reputation: 33603

d2 <- cbind((a+b+c)[, -3], c[, 3])
all.equal(d, d2) # TRUE

NB. It is not good practice to name an object c in R.

Upvotes: 1

Related Questions