Search code examples
rmatrixsumcol

How can we add two matrices with different rows and columns in R?


I have two matrices:For example

temp1 <- matrix(c(1,2,3,4,5,6),2,3,byrow = T)
temp2 <- matrix(c(7,8,9),1,3,byrow = T)

temp1

       [,1] [,2] [,3]
 [1,]    1    2    3
 [2,]    4    5    6

temp2

       [,1] [,2] [,3]
 [1,]    7    8    9

I have two matrices with the same number of rows, but with different rows. I would like to add these two matrices as follows. I wonder if there is a way to add R without for statements and apply functions.

temp <- do.call(rbind,lapply(1:2,function(x){temp[x,]+temp2}))

temp

       [,1] [,2] [,3]
 [1,]    8   10   12
 [2,]   11   13   15

This example is simple, but in practice I need to do the above with a 100 * 100 matrix and a 1 * 100 matrix. In this case, it takes too long, so I do not want to use for statements and apply functions.


Solution

  • You can use ?sweep:

    temp1 <- matrix(c(1,2,3,4,5,6),2,3,byrow = T)
    temp2 <- matrix(c(7,8,9),1,3,byrow = T)
    sweep(temp1, 2, temp2, '+')
    

    Unfortunately the help for sweep is really difficult to understand, but in this example you apply the function ´+´ with argument ´temp2´ along the second dimension of temp1.

    For more examples, see: How to use the 'sweep' function