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

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Tue Jul 19 21:39:09 CEST 2011


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of RichardLang
> Sent: Tuesday, July 19, 2011 11:44 AM
> To: r-help at r-project.org
> Subject: [R] calculating the mean of a random matrix (by row) and some
> general questions
> 
> 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".
> 
> 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? =)
> 
> Richard
> 

Richard,

If you have a matrix, M, with n rows and m columns, you can use the apply() function to get either row or column means

> n <- 10 
> m <-3
> M <- matrix(rnorm(m*n),n,m)
> M
            [,1]        [,2]       [,3]
 [1,]  0.6239267 -0.70546496  0.3682918
 [2,] -0.7326689 -1.86571052 -0.2899552
 [3,]  0.7778313 -1.01227191  0.7735718
 [4,]  0.8336683 -0.07755214 -0.1375798
 [5,] -1.6134414  0.12088648 -0.4064939
 [6,] -0.2578007  0.45142456 -1.0197297
 [7,]  1.0108260 -0.24933408 -0.4083304
 [8,] -0.7936603 -0.67286769 -0.8666802
 [9,]  1.0054039  2.52498995  1.0915742
[10,] -0.1610073  0.43504924  2.4288474
> rowMeans <- apply(M,1,mean)
> rowMeans
 [1]  0.09558452 -0.96277820  0.17971042  0.20617876 -0.63301628 -0.27536860
 [7]  0.11772050 -0.77773605  1.54065601  0.90096312
> colMeans <- apply(M,2,mean)
> colMeans
[1]  0.06930777 -0.10508511  0.15335160
>

I will let others describe how they use R.



Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204




More information about the R-help mailing list