subtract a constant vector from each row in a matrix in r

前端 未结 5 1764
终归单人心
终归单人心 2020-12-14 00:36

I have a matrix with 5 columns and 4 rows. I also have a vector with 3 columns. I want to subtract the values in the vector from columns 3,4 and 5 respectively at each row o

5条回答
  •  死守一世寂寞
    2020-12-14 01:20

    Perhaps not that elegant, but

    b <- matrix(rep(1:20), nrow=4, ncol=5)
    x <- c(5,6,7)
    
    b[,3:5] <- t(t(b[,3:5])-x)
    

    should do the trick. We subset the matrix to change only the part we need, and we use t() (transpose) to flip the matrix so simple vector recycling will take care of subtracting from the correct row.

    If you want to avoid the transposed, you could do something like

    b[,3:5] <- b[,3:5]-x[col(b[,3:5])]
    

    as well. Here we subset twice, and we use the second to get the correct column for each value in x because both those matrices will index in the same order.

    I think my favorite from the question that @thelatemail linked was

    b[,3:5] <- sweep(b[,3:5], 2, x, `-`)
    

提交回复
热议问题