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

前端 未结 5 1759
终归单人心
终归单人心 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:30

    A simple solution:

    b <- matrix(rep(1:20), nrow=4, ncol=5)
    c <- c(5,6,7)
    
    for(i in 1:nrow(b)) {
      b[i,3:5] <- b[i,3:5] - c
    }
    

提交回复
热议问题