Sorry if this will seem trivial, but after searching the internet for some time I couldn't come upon a solution.
I have a matrix and a factor vector associated with columns. The goal is to get rowMeans for all factors separately and maintain the original matrix structure. So probably it would be something like ave() but working on 2 dimensional arrays.
Here is a crude demonstration:
(mat <- rbind(1:5,6:10,11:15))
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
groups <- c(1,1,1,2,2)
mat[,groups==1] <- rowMeans(mat[,groups==1]) # I am asking about this part
mat[,groups==2] <- rowMeans(mat[,groups==2]) # ...
mat
[,1] [,2] [,3] [,4] [,5]
[1,] 2 2 2 4.5 4.5
[2,] 7 7 7 9.5 9.5
[3,] 12 12 12 14.5 14.5
In practice this matrix would have millions of rows (and less columns). So solutions that work row-by-row might be too slow.
I am on the way to writing my own function, but this seems like something that might have an easy one-line solution.