Error in ggplot2::autoplot() function with linear model(lm) when na.action = na.exclude

I first create an test dataset and then fit a model as follows:

#mtcars data set
test <- mtcars

#adding just one NA in the cyl column
test[2, 2] <- NA

#running linear model 
mod <- lm(data = test, formula=mpg ~ cyl, na.action = na.exclude)

#saving residuals
test$res <- residuals(mod)

#outoplot.lm
ggfortify:::autoplot.lm(object=mod, which = c(1,2,3,4,5))

 #using autoplot funtion
ggplot2::autoplot(which = c(1, 2, 3, 4,5,6),  object = mod)

#I get the following error
Error in `$<-.data.frame`(`*tmp*`, .hat, value = c(0.0326370757180157,  : 
  replacement has 32 rows, data has 31

Is there a work around or an an alternative function that will give me all the six residual plots without removing na.action = na.exclude from the model?.

Currently you're passing a model object (type lm) to autoplot(), which isn't supported. Here's what I get when I run your code:

test <- mtcars

# adding just one NA in the cyl column
test[2, 2] <- NA

# running linear model
mod <- lm(data = test, formula = mpg ~ cyl, na.action = na.exclude)

# saving residuals
test$res <- residuals(mod)

# using autoplot funtion
last_autoplot <- ggplot2::autoplot(which = c(1, 2, 3, 4, 5, 6), object = mod)
#> Error: Objects of type lm not supported by autoplot.

Created on 2018-10-12 by the reprex package (v0.2.1.9000)

1 Like

Did you define an autoplot.lm function? If so, please provide it.

1 Like