subtract the values from one matrix by row for each column of another matrix

So I have a matrix_1 (columns = 250 and rows =800) and another matrix_2 (columns = 1 and rows = 800). I need to subtract the values of the matrix_2 by row for each column of matrix_1 in R. How can I do this? The number of columns is too big to go one by one.

>Solution :

You could use m1 - c(m2). The c() reduces a 1-column matrix to a vector. When it is subtracted from a matrix, it will recycle to the same dimention of that matrix.

> m1 <- matrix(1:15, 5, 3)

     [,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15

> m2 <- matrix(1:5, 5, 1)

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

> m1 - c(m2)

     [,1] [,2] [,3]
[1,]    0    5   10
[2,]    0    5   10
[3,]    0    5   10
[4,]    0    5   10
[5,]    0    5   10

Leave a Reply