Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading