[R] Odp: means and variances of several groups in the matrix

Petr PIKAL petr.pikal at precheza.cz
Mon Apr 21 12:40:15 CEST 2008


Hi

r-help-bounces at r-project.org napsal dne 21.04.2008 09:03:30:

> 
> Dear R users, 
> 
> I have 32 observations in data x.  After sorting this, I want to compute
> means and variances of 3 groups divided by "nr".
> 
> Actually, the number of groups is flexible.  Any suggestion will be 
greatly
> appreciated. 
> 
> Kathryn Lord
> 
> 
---------------------------------------------------------------------------
> x=rnorm(32)
> y=sort(x)
> 
> nr=matrix(c(12,11,10,10,10,11),2,3)
> > nr
>      [,1] [,2] [,3]
> [1,]   12   10   10    -> sum=32
> [2,]   11   10   11    -> sum=32
> 
> For the 1st row in "nr", index of y = (1,..,12,   13,...,23,   24,...32)
> 
> I want to compute means and variances for 3 groups 
> 
> (1st group is 1 through 12; 2nd group is 13-23; 3rd group is 24-32)
> 
> 
> For the 2nd row in "nr", index of y = (1,..,11,   12,...,22,   23,...32)
> 
> also, I want to compute means and variances for 3 groups 
> 
> (1st group is 1 through 11; 2nd group is 12-22; 3rd group is 23-32)
> 

If you know that your vector is sorted you can do

sapply(split(y,rep(1:3, times=nr[1,])), mean)

Regards
Petr


> 
> 
> -- 
> View this message in context: 
http://www.nabble.com/means-and-variances-of-
> several-groups-in-the-matrix-tp16803939p16803939.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list