[R] How to calculate the row wise means for grouped columns in matrix?

Benilton Carvalho beniltoncarvalho at gmail.com
Fri Jan 15 16:09:17 CET 2010


adapted from the help files of rowsum

x <- matrix(runif(100), ncol=5)
group <- sample(1:8, 20, TRUE)
xsum <- rowsum(x, group)
sweep(xsum, 1, table(group), "/")

or

aggregate(x, list(group), mean)[-1]

b

2010/1/15 Joel Fürstenberg-Hägg <joel_furstenberg_hagg at hotmail.com>:
>
> Hi all,
>
>
>
> I want to calculate the row wise mean of groups of columns in a matrix M. All columns belonging to the same group have the same column name. My idea is to create a new vector V containing these column names, but after first removing the duplicates. Then I would calculate the means using for instance rowMean() and by comparing the column names of M with the vector V, getting the indices of the columns to use.
>
>
>
> What do you think, is it a good idea or not? If yes, any suggestions how to do it? If no, is there any alternative solution that might work better?
>
>
>
>
>
>
>
> All the best,
>
>
>
> Joel
>
> _________________________________________________________________
> Lagra alla dina foton på Skydrive. Det är enkelt och säkert!
> http://www.skydrive.live.com
>        [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list