# Subtract maximum per row in R

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!

Sotos
answered question

## Have an answer?

JD

One way could be

`mat - apply(mat, 1, max)`