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

Viewed 34

I have a 800x250 matrix m1 and another 800x1 matrix m2. I need to subtract the values of the m2 by row for each column of m1 in R. How can I do this? The number of columns is too big to go one by one.

1 Answers

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
Related