[R] Calculate Mean of Column Vectors?

Marc Schwartz MSchwartz at MedAnalytics.com
Tue Jan 11 05:03:36 CET 2005


On Mon, 2005-01-10 at 22:45 -0500, Thomas Hopper wrote:
> Hello,
> 
> I've got an array defined as y <- rnorm(3000), dim(y) <- c(3, 1000).
> 
> I'd like to produce a 1000-element vector z that is the mean of the 
> corresponding elements of y (like z[1,1] <- mean(y[1,1], y[2,1], 
> y[3,1])), but being new to R, I'm not sure how to do this for all 
> elements at once (or, at least, simply). Any help is appreciated.
> 
> Thanks,
> 
> Tom

# You can create 'y' in one step here
y <- matrix(rnorm(3000), ncol = 1000)

# get the column means
z <- colMeans(y)

> str(z)
 num [1:1000] -0.5664  0.8232 -0.0138 -0.5511  1.0224 ...


See ?colMeans for more info.


HTH,

Marc Schwartz




More information about the R-help mailing list