[R] calculating the mean of a random matrix (by row) and some general questions
dwinsemius at comcast.net
Tue Jul 19 22:28:53 CEST 2011
On Jul 19, 2011, at 4:03 PM, RichardLang wrote:
> Thanks for your advice!
> I found another method to solve my problem (on page 20 of the manual
> =) ).
> Here's my code
In r-help most of the readers and most of the regular responders are
reading this as a mailing list posting.... not on Nabble and it looks
like you are responding to yourself. I remember what I wrote but the
rest of the readers probably don't and no one can tell if you are
reponding to me or to Nordlund. You are asked in the Posting Guide to
provide context and it's not that hard in Nabble.
> # Set n and m to whatever you want
> n = 25
> m = 10
> # Build a random vector (here with exponential distribution) with
> lenght of
> x = rexp(n*m,1)
> # Set up a factor in order to group x into pieces each of size ten
> y = factor( rep(1:n, each = m) )
> # tapply will apply mean to each group..
> result = tapply(x,y,mean)
There are many ways to skinning that cat:
rowMeans( matrix( rexp(n*m,1), ncol=10) )
This will be much faster than Nordlund's answer on bigger tasks,
because the row/colMeans and row/colSums functions are tweaked to be
fast, whereas there is a lot of overhead with the apply functions.
David Winsemius, MD
West Hartford, CT
More information about the R-help