[R] means and variances of several groups in the matrix
Julian Burgos
jmburgos at u.washington.edu
Fri Apr 25 02:35:44 CEST 2008
Hy Katie,
There are many ways to do this. A simple one is to create a vector of
the same length than your 'x' vector, containing a group label.
> group=rep(c(1,2,3),times=nr[1,])
Then you can use tapply to apply a function (in this case mean and
variance) of the values of x within each group.
> means=tapply(x,group,mean)
> vars=tapply(x,group,var)
> means
1 2 3
-0.14711206 0.28314274 -0.07861427
> vars
1 2 3
1.4584971 0.3611996 0.6300624
Julian
kathie wrote:
> 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)
>
>
>
More information about the R-help
mailing list