2

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)
Dharman
  • 21,838
  • 18
  • 57
  • 107
seabysalt
  • 47
  • 3
  • Possible duplicate of [How to compare a model with no random effects to a model with a random effect using lme4?](https://stackoverflow.com/questions/24019807/how-to-compare-a-model-with-no-random-effects-to-a-model-with-a-random-effect-us) – AkselA Sep 17 '19 at 08:36
  • @AkselA This answer is quite old. I wouldn't consider it up-to-date concerning the current lme4 version (although it's points are still valid). – Roland Sep 17 '19 at 08:41

1 Answers1

1

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.

Roland
  • 117,893
  • 9
  • 163
  • 255