Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S4 object with class lmerModLmerTest

Hi all, I want to obtain diagnosis plots from the following codes with R version 4.0.2 and RStudio Version 1.3.1056, error information as follows:
Error: data must be a data frame, or other object coercible by fortify(), not an S4 object with class lmerModLmerTest

The strange thing is that the following codes work well with R version 3.6.3.

By the way, I need use the package lmerTest and I want to get diagonis plots, such as qqplot, Residual vs Fitted Plot. Any suggestions? Thanks!

john <- read.table("http://stat.ethz.ch/~meier/teaching/data/john.dat", header = TRUE)
john[, "plot"] <- factor(john[, "plot"])
#https://stat.ethz.ch/~meier/teaching/anova/split-plot-designs.html

library(lme4)
library(Matrix)
library(lmerTest)
library(ggplot2)
fit <- lmer(mass ~ fertilizer * variety + (1 | plot), data = john)
p1 <-ggplot(fortify(fit), aes(.fitted, .resid))+geom_point()
# fortify(fit), Error
p1 + stat_smooth(method="loess") + 
  geom_hline(yintercept=0, col="red", linetype="dashed") +
  xlab("Fitted values") + 
  ylab("Residuals") + 
  ggtitle("Residual vs Fitted Plot") + 
  theme_bw()
plot(fit)
#work, obtain Residual vs Fitted Plot

Welcome yang6,
The package broom.mixed is an extension of the broom package that handles
mixed effect models. Like broom, you can augment the data.frame that's
passed by default into the lmer model fit.

library(lmerTest)
#> Loading required package: lme4
#> Loading required package: Matrix
#> 
#> Attaching package: 'lmerTest'
#> The following object is masked from 'package:lme4':
#> 
#>     lmer
#> The following object is masked from 'package:stats':
#> 
#>     step
library(Matrix)
library(ggplot2)
library(broom.mixed)
#> Registered S3 method overwritten by 'broom.mixed':
#>   method      from 
#>   tidy.gamlss broom

john <- read.table("http://stat.ethz.ch/~meier/teaching/data/john.dat", header = TRUE)
john[, "plot"] <- factor(john[, "plot"])
#https://stat.ethz.ch/~meier/teaching/anova/split-plot-designs.html


fit <- lmer(mass ~ fertilizer * variety + (1 | plot), data = john)

fit_augmented <- augment(fit)

p1 <-ggplot(fit_augmented, aes(.fitted, .resid))+
  geom_point()

p1 + stat_smooth(method="loess") + 
  geom_hline(yintercept=0, col="red", linetype="dashed") +
  xlab("Fitted values") + 
  ylab("Residuals") + 
  ggtitle("Residual vs Fitted Plot") + 
  theme_bw()
#> `geom_smooth()` using formula 'y ~ x'

  
qqnorm(fit_augmented[[".resid"]])

Created on 2020-07-24 by the reprex package (v0.3.0)

2 Likes

Thank you! @technocrat

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

@jrmuirhead nailed it. FYI: fortify is now in bad odor. See the doc

Thank you very much for your help! @jrmuirhead