[R] Calculate Mean of Column Vectors?
Henrik Bengtsson
hb at maths.lth.se
Tue Jan 11 05:17:05 CET 2005
See ?apply. Example
y <- rnorm(3000), dim(y) <- c(3, 1000)
my <- apply(y, MARGIN=2, FUN=mean, na.rm=TRUE)
to calculate the mean over the 2nd index, that is, for each column, and pass
argument na.rm=TRUE to each call to mean(). This is in practice the same as
my <- rep(NA, ncol(y))
for (kk in 1:ncol(y)) my[kk] <- mean(y[,kk], na.rm=TRUE)
but apply() is to prefer when you get used to it.
Best wishes
Henrik Bengtsson
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Thomas Hopper
> Sent: Tuesday, January 11, 2005 4:46 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Calculate Mean of Column Vectors?
>
>
> 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
More information about the R-help
mailing list