[R] get mean of several rows

Liaw, Andy andy_liaw at merck.com
Thu Dec 4 14:25:27 CET 2003


1. Using rowMeans() is more efficient for computing row means.

2. "Mean of five rows" is the same as "mean of the five row means"
(exception: if you have NAs, and set na.rm=TRUE).  So you can just do
something like:

k <- ceiling(nrow(x) / 5)
ktimes <- if (rem <- nrow(x) %% 5) c(rep(5, k-1), rem) else rep(5, k)
mean5row <- tapply(rowMeans(x), rep(1:k, ktimes))

(This is untested!)

HTH,
Andy

> From: Jan Wantia
> 
> Dear all!
> 
> After hours of trying around, I gave up:
> 
> I have a 2-dimensional array, and I know how to split it into 
> its rows 
> and how to get the mean for every row using 'sapply'.
> But what I want is to calculate the mean over the first n 
> rows, and then 
> the second n rows, etc., so that I get a vector like:
> 
> v == mean1(row 1:5), mean2(row6:10),...
> 
> (trivial, you might say. I find it rather mind-boggling, 
> though: I tried 
> to get the mean from the array before splitting it, after 
> splitting it, 
> looping through it with for-loops...I feel like an idiot by 
> now; looks 
> like I missed a crucial point of how 'R' works.)
> 
> Thanks a lot in advance!
> -- 
> 
> ______________________________________________________
> 
> Jan Wantia
> Dept. of Information Technology, University of Zürich
> Andreasstr. 15
> CH 8050 Zürich
> Switzerland
> 
> Tel.:     +41 (0) 1 635 4315
> Fax:     +41 (0) 1 635 45 07
> email: wantia at ifi.unizh.ch




More information about the R-help mailing list