# [R] calculating the mean of a random matrix (by row) and some general questions

David Winsemius dwinsemius at comcast.net
Tue Jul 19 21:50:54 CEST 2011

```On Jul 19, 2011, at 2:43 PM, RichardLang wrote:

> Hi everyone!
>
> I'm trying to teach myself R in order to do some data analysis. I'm a
> mathematics student and (only) familiar with matlab and latex. I'm
> working
> trough the "official" introduction to R at the moment, while
> simultaneously
> solving some exercises I found in the web. Before I post my (probably
> stupid) question, I'd like to ask you for some general advice. How
> do you
> work with R? Is it like in matlab, that you write your functions
> with a lot
> of loops etc. in a textfile and then run it? Or do you just prepare
> your
> data and then use the functions provided by R (plot, mean etc) to
> get some
> analysis? I'd be very thankfull for some of your thoughts about
> "approaches".

In R one generally tries to avoid loops. There are many functions that
accept vector and matrix arguments and retrun similarly structured
results. My impression was that that was also true in Matlab and that
many of the loop-less (the R term is "vectorized") constructs were
very similar. Matrix math and all that jazz.

>
> Now the question: I'm trying to build a vector with n entries, each
> consisting of the mean of m random numbers (exponential distributed
> for
> example). My approach was to construct a nxm random matrix and then to
> somehow take the mean of each row. But in the mean function there is
> no
> parameter to do this, so the intended approach of R is probably
> different..
> any ideas? =)

Generally when performing a repeated task involving random simulation
one turns to the replicate function. To generate 5 means of length 10,
random exponentially distributed vectors:

> replicate(5, mean( rexp(10, rate= 1.5) ) )
 1.0786732 0.7196179 0.7179612 0.5024858 0.4624592

--
David.

>
> Richard
>
> --
> View this message in context: http://r.789695.n4.nabble.com/calculating-the-mean-of-a-random-matrix-by-row-and-some-general-questions-tp3678964p3678964.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help