R-Anova在多级分析中不起作用-“未为此S4类定义$运算符”

时间:2019-09-17 08:25:54

标签: r lme4

尝试执行与多级分析有关的方差分析时,在R中运行代码时遇到问题。我总是收到错误:“未为此S4类定义$运算符”。非常感谢您的帮助!

## 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)

非常感谢!

萨拉

1 个答案:

答案 0 :(得分:0)

只需颠倒参数的顺序即可:

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

技术说明:

anova是S3泛型。 S3方法分派根据作为第一个参数传递的对象的类进行工作。如果首先放置lm适合,则会调用anova.lm并且它不能处理“ merMod”对象。如果您先将lmer放在合适位置,则会调用anova.merMod,并且此方法还可以处理“ lm”对象。