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

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, `-`)

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
}

This is exactly what sweep was made for:

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

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

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    5    4    7   10
#[2,]    2    6    5    8   11
#[3,]    3    7    6    9   12
#[4,]    4    8    7   10   13

..or even without subsetting or reassignment:

sweep(b, 2, c(0,0,x))

Another way, with apply:

b[,3:5] <- t(apply(b[,3:5], 1, function(x) x-c))

Tags:

Matrix

R

Vector