2

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.

2
  • You can transpose the 100x100 matrix, using t, then add the 1*100 matrix with as.numeric, then transpose the result. i.e t(t(temp1) + as.numeric(temp2)) Sep 27, 2018 at 10:33
  • 2
    Alternatively, you can expand the later one to the same shape as the former: temp1 + temp2[rep(1, nrow(temp1)), ]
    – mt1022
    Sep 27, 2018 at 10:53

1 Answer 1

2

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

1
  • Thank you for your knowledge. This has been a great help to me ! Sep 27, 2018 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.