I got a problem running my code in R when trying to do an anova related to my multilevel analysis. I always get the error:
$ operator not defined for this S4 class
## Model 0: Model without teams - grand-mean-centered
h2_0_gmc <- lm(PSS_mean ~ PCT_mean_gmc, data = dat_h1_2)
## Model 1: Model with teams - fixed intercept, random slope - grand-mean-centered
h2_1_gmc <- lmer(PSS_mean ~ PCT_mean_gmc + (1 | teamcode), data = dat_h1_2)
## Model 2: Model with teams - random intercept, random slope - grand-mean-centered
h2_2_gmc <- lmer(PSS_mean ~ PCT_mean_gmc + (PCT_mean_gmc | teamcode), data = dat_h1_2)
## Comparison of models
anova(h2_0_gmc, h2_1_gmc, h2_2_gmc)
Simply reverse the order of arguments:
library(lme4)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
fm0 <- lm(Reaction ~ Days, sleepstudy)
anova(fm0, fm1)
#Error: $ operator not defined for this S4 class
anova(fm1, fm0)
#refitting model(s) with ML (instead of REML)
#Data: sleepstudy
#Models:
#fm0: Reaction ~ Days
#fm1: Reaction ~ Days + (Days | Subject)
# Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq)
#fm0 3 1906.3 1915.9 -950.15 1900.3
#fm1 6 1763.9 1783.1 -875.97 1751.9 148.35 3 < 2.2e-16 ***
#---
#Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Technical explanation:
anova
is an S3 generic. S3 method dispatch works according to the class of the object passed as the first argument. If you put the lm
fit first, anova.lm
is called and it can't deal with "merMod" objects. If you put the lmer
fit first, anova.merMod
is called and this method can also deal with "lm" objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With