I have a data set with 1002 subjects and 501 families, and I would like to estimate the % variance explained by "family" on a dependent variable.
To make it easier, lets say I want to find the % variance explained by "Batch" in the follow data set:
Test data
set.seed(1231)
batch <- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
yield <- c(34,36,35,68,71,72,75,87,97,72,74,73,79,81,79)
age <- rnorm(15, mean = 20, sd = 1)
bmi <- rnorm(15, mean = 32, sd = 1.2)
mydata <- data.frame(batch, yield, age, bmi)
mydata$batch <- factor(mydata$batch)
str(mydata)
Approach one:
I regressed "yield" against covariates "Age" and "bmi", then extract the residuals. Using the residuals, I estimated the R$^2$ of "Batch"
Approach two:
I could estimate the R$^2$ of "Batch" with a mixed model, using "Batch" as a random effect. (The original data has 501 families and thus I want to make it as a random effect)
My question is:
I do not able to get similar R$^2$ of "Batch" from the 2 different approaches above (0.6915 vs 0.937).
I wonder anyone could give me a help here? I thought about this for 2 days and still have no ideas. Would be very gladly for the help. :-)
R code
# Approach one: Extract residual and estimate R$^2$ of "Batch"
lmaovresid <- lm(yield ~ age + bmi, data = mydata)
mydata$Yresid <- lmaovresid$residuals
lmaov2 <- lm(Yresid ~ batch, data = mydata)
anova(lmaov2)
# Response: yieldresid
# Df Sum Sq Mean Sq F value Pr(>F)
# batch 4 2535.9 633.97 5.6048 0.01245 *
# Residuals 10 1131.1 113.11
# Therefore, R$^2$ of "Batch" = 2535.9/(2535.9+1131.11) = 0.6915
# Approach two: mixed model using "batch" as random effect
library(lme4)
mixed2 <- lmer(yield ~ age + bmi + (1|batch), data = mydata)
summary(mixed2)
# Random effects:
# Groups Name Variance Std.Dev.
# batch (Intercept) 391.95 19.798
# Residual 31.52 5.614
# Number of obs: 15, groups: batch, 5
## So:
## MS of "Batch" = 31.52 + 15/5*(391.95) = 1207.37
## SS of "Batch" = 1207.37 * 4 = 4829.48
## SS of residual = 31.52 * 10 = 315.2
anova(mixed2)
# Analysis of Variance Table
# Df Sum Sq Mean Sq F value
# age 1 2.7085 2.7085 0.0859
# bmi 1 1.4369 1.4369 0.0456
## Therefore, R^2 of "Batch"
## = 4829.48/ (4829.48+315.2+2.7085+1.4369) = 0.937