I would like to perform column-wise normalization of a matrix in R. Given a matrix m, I want to normalize each column by dividing each element by the sum of the column. One (hackish) way to do this is as follows:

m / t(replicate(nrow(m), colSums(m)))


Is there a more succinct/elegant/efficient way to achieve the same task?

This is what sweep and scale are for.

sweep(m, 2, colSums(m), FUN="/")
scale(m, center=FALSE, scale=colSums(m))


Alternatively, you could use recycling, but you have to transpose it twice.

t(t(m)/colSums(m))


Or you could construct the full matrix you want to divide by, like you did in your question.  Here's another way you might do that.

m/colSums(m)[col(m)]


And notice also caracal's addition from the comments:

m %*% diag(1/colSums(m))

