简体   繁体   中英

R Subtract elements from one matrix row from another matrix

So take for example these to matrices.

mat1<- matrix(c(1:30),ncol=3)

     [,1] [,2] [,3]
[1,]    1   11   21
[2,]    2   12   22
[3,]    3   13   23
[4,]    4   14   24
[5,]    5   15   25
[6,]    6   16   26
[7,]    7   17   27
[8,]    8   18   28
[9,]    9   19   29
[10,]   10   20   30



mat2 <- matrix(c(5,rep(1,9),5.4,rep(2,9),5.5,rep(3,9)),ncol=3)

    [,1] [,2] [,3]
[1,]    5  5.4  5.5
[2,]    1  2.0  3.0
[3,]    1  2.0  3.0
[4,]    1  2.0  3.0
[5,]    1  2.0  3.0
[6,]    1  2.0  3.0
[7,]    1  2.0  3.0
[8,]    1  2.0  3.0
[9,]    1  2.0  3.0

I am trying to subtract the first column of mat2 from every row in mat1 , however with the code:

mat1[,1:3]-mat2[1,1:3]

      [,1] [,2] [,3]
 [1,] -4.0  5.6 15.5
 [2,] -3.4  6.5 17.0
 [3,] -2.5  8.0 17.6
 [4,] -1.0  8.6 18.5
 [5,] -0.4  9.5 20.0
 [6,]  0.5 11.0 20.6
 [7,]  2.0 11.6 21.5
 [8,]  2.6 12.5 23.0
 [9,]  3.5 14.0 23.6
[10,]  5.0 14.6 24.5

You don't really get that result. I don't fully understand what's happening here... It seems as if the elements of the first row of mat2 are alternating in the subtraction process?

It works with

matrix(c(mat1[,1]-mat2[1,1],mat1[,2]-mat2[1,2],mat1[,3]-mat2[1,3]),ncol=3)

but for the dimension of my data it gets really messy.

Any ideas?

If you want to use vector recycling, you need to be aware that matrices are filled column-wise and recycling is done in that direction. So, you need to transpose the matrix:

t(t(mat1)-mat2[1,])
#      [,1] [,2] [,3]
# [1,]   -4  5.6 15.5
# [2,]   -3  6.6 16.5
# [3,]   -2  7.6 17.5
# [4,]   -1  8.6 18.5
# [5,]    0  9.6 19.5
# [6,]    1 10.6 20.5
# [7,]    2 11.6 21.5
# [8,]    3 12.6 22.5
# [9,]    4 13.6 23.5
#[10,]    5 14.6 24.5

Or you could do:

 mat1-mat2[1,col(mat2)]
   #      [,1] [,2] [,3]
   #[1,]   -4  5.6 15.5
   #[2,]   -3  6.6 16.5
   #[3,]   -2  7.6 17.5
   #[4,]   -1  8.6 18.5
   #[5,]    0  9.6 19.5
   #[6,]    1 10.6 20.5
   #[7,]    2 11.6 21.5
   #[8,]    3 12.6 22.5
   #[9,]    4 13.6 23.5
  #[10,]    5 14.6 24.5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM