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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.