##Hierarchical sampling and variance components analysis 
library(lmerTest)
## Loading required package: Matrix
## Loading required package: lme4
## 
## Attaching package: 'lmerTest'
## The following object is masked from 'package:lme4':
## 
##     lmer
## The following object is masked from 'package:stats':
## 
##     step
ex.data<-read.table("C:/jenn/teaching/stat579/data/hredata.txt",header=TRUE)
str(ex.data)
## 'data.frame':    720 obs. of  7 variables:
##  $ subject  : num  0.662 2.879 8.588 11.666 15.475 ...
##  $ town     : Factor w/ 5 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ district : Factor w/ 3 levels "d1","d2","d3": 1 1 1 1 1 1 1 1 1 1 ...
##  $ street   : Factor w/ 4 levels "s1","s2","s3",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ family   : Factor w/ 3 levels "f1","f2","f3": 1 1 1 1 2 2 2 2 3 3 ...
##  $ gender   : Factor w/ 2 levels "female","male": 2 2 1 1 2 2 1 1 2 2 ...
##  $ replicate: int  1 2 1 2 1 2 1 2 1 2 ...
head(ex.data)
##      subject town district street family gender replicate
## 1  0.6619806    A       d1     s1     f1   male         1
## 2  2.8791950    A       d1     s1     f1   male         2
## 3  8.5882370    A       d1     s1     f1 female         1
## 4 11.6661800    A       d1     s1     f1 female         2
## 5 15.4754800    A       d1     s1     f2   male         1
## 6 16.2973600    A       d1     s1     f2   male         2
names(ex.data)
## [1] "subject"   "town"      "district"  "street"    "family"    "gender"   
## [7] "replicate"
attach(ex.data)
myfit<-lmer(subject~1+(1|town/district/street/family/gender))
summary(myfit)
## summary from lme4 is returned
## some computational error has occurred in lmerTest
## Linear mixed model fit by REML ['lmerMod']
## Formula: subject ~ 1 + (1 | town/district/street/family/gender)
## 
## REML criterion at convergence: 3337.3
## 
## Scaled residuals: 
##      Min       1Q   Median       3Q      Max 
## -2.64600 -0.47627 -0.06009  0.47532  2.35647 
## 
## Random effects:
##  Groups                                   Name        Variance Std.Dev.
##  gender:(family:(street:(district:town))) (Intercept) 15.3450  3.9173  
##  family:(street:(district:town))          (Intercept)  3.6985  1.9232  
##  street:(district:town)                   (Intercept)  2.2197  1.4899  
##  district:town                            (Intercept)  1.2812  1.1319  
##  town                                     (Intercept)  1.3239  1.1506  
##  Residual                                              0.8548  0.9245  
## Number of obs: 720, groups:  
## gender:(family:(street:(district:town))), 360; family:(street:(district:town)), 180; street:(district:town), 60; district:town, 15; town, 5
## 
## Fixed effects:
##             Estimate Std. Error t value
## (Intercept)    8.011      0.672   11.92
#standard error
sds<-c(0.9245321,1.150604,1.131932,1.489864,1.923191,3.917264)
#variance
vars<-sds^2
100*vars/sum(vars)
## [1]  3.457313  5.354840  5.182453  8.978173 14.960274 62.066948