[R] get mean of several rows

Eric Lecoutre lecoutre at stat.ucl.ac.be
Thu Dec 4 14:43:25 CET 2003


Take a look at tapply and %/% which could help you to create indices for 
groups.

 > x=cbind(id=1:23,var1=rnorm(23))
 > tapply(x[,"var1"],1:length(x[,"var1"])%/%5,rowMeans)
            0            1            2            3            4
  0.393473633  0.412297253 -0.221925003 -0.005212217 -1.564881727

If your data has severall variables, also look at aggregate

 > x=cbind(var1=rnorm(23),var2=rnorm(23))
 > aggregate(x,by=list(groups=1:dim(x)[1]%/%5),FUN=mean)

(and then you can call rowMeans on the result)

Eric


At 14:03 4/12/2003, Jan Wantia wrote:
>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
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help



--------------------------------------------------
L'erreur est certes humaine, mais un vrai désastre
nécessite un ou deux ordinateurs. Citation anonyme
--------------------------------------------------
Eric Lecoutre
Informaticien/Statisticien
Institut de Statistique / UCL

TEL (+32)(0)10473050       lecoutre at stat.ucl.ac.be
URL http://www.stat.ucl.ac.be/ISpersonnel/lecoutre




More information about the R-help mailing list