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

From: Julian Burgos <jmburgos_at_u.washington.edu>
Date: Thu, 24 Apr 2008 17:35:44 -0700

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)
>
>
>

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. Received on Fri 25 Apr 2008 - 00:47:18 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 25 Apr 2008 - 01:30:31 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive