[R] within-groups variance and between-groups variance

S Ellison S.Ellison at LGCGroup.com
Fri Aug 26 13:01:37 CEST 2011


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Coghlan, Avril
> Sent: 25 August 2011 16:02
> To: r-help at r-project.org
> Cc: Coghlan, Avril
> Subject: [R] within-groups variance and between-groups variance
> 
> Hello,
> 
> I have been looking for functions for calculating the 
> within-groups variance and between-groups variance, for the 
> case where you have several numerical variables describing 
> samples from a number of groups.

There doesn't seem to be a function in the core distribution for estimating variance components from linear model anova. If I want to do this from a balanced nested design I usually do something like 
a <- anova(lm(Sepal.Length~Species, data=iris))
a
s2.within<-a[2,3]
s2.between <- (a[1,3]-a[2,3])/( (1+a[1,1]+a[2,1])/(a[1,1]+1))

This is just the usual balanced one-way ANOVA estimate of variance components from the expected mean squares, with the within-group replicate number calculated from the degrees of freedom. 

However, you can very easily, and more generally, use lme to obtain the REML estimates,:

library(nlme)
iris.lme <- lme(Sepal.Length~1, random=~1|Species, data=iris)
VarCorr(iris.lme) 

In this instance, because of the model specification the (Intercept) term gives you the between-species component of variance, and the residual term gives the within-species term. For this particular example, too, the REML estimates are identical to the linear model version above to six or so places. 

S Ellison
LGC


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}



More information about the R-help mailing list