Subtract maximum per row in R

2942 views r
3

Suppose you want to subtract the maximum value of each row of a matrix from the respective row. You could do it using a loop like this:

# create matrix
mat <- matrix(rnorm(100),ncol=5,nrow=20)

for(i in 1:nrow(mat)){    #for each row
  row.max <- max( mat[i,] ) #take the maximum of the row
  mat[i,] <- mat[i,] - row.max  #subtract it from the row
}

I am thinking about a way to do this in a vectorized manner, maybe using max.col() , however, I could not come up with something so far. Any ideas?

Thanks!

answered question

One way could be mat - apply(mat, 1, max)

1 Answer

8

You can use library(matrixStats) and simply use,

mat - rowMaxs(mat)

posted this

Have an answer?

JD

Please login first before posting an answer.