sinhrks / ggfortify

Define fortify and autoplot functions to allow ggplot2 to handle some popular R packages.
Other
527 stars 65 forks source link

autoplot.lm(which = 2) fails when residuals have class AsIs #202

Closed richierocks closed 4 years ago

richierocks commented 4 years ago

System information

Describe the problem

If the response variable in a linear model created with lm() is wrapped in I(), then the residuals have type AsIs, which causes an error in autoplot.lm() when which = 2.

Source code / logs / plots

library(ggplot2)
library(ggfortify)

# Create a linear regression model with response wrapped in I()
mdl_cars <- lm(I(dist ^ 2) ~ speed, data = cars)

# Automatic Q-Q plot
autoplot(mdl_cars, which = 2, ncol = 1)
#> Error in UseMethod("rescale"): no applicable method for 'rescale' applied to an object of class "AsIs"

# Remove the class of the residuals and try again
class(mdl_cars$residuals) <- NULL
autoplot(mdl_cars, which = 2, ncol = 1)

I think that the simplest fix is that autoplot.lm() should just drop the class of the residuals, so it is always dealing with a numeric vector.

terrytangyuan commented 4 years ago

Thanks for the detailed and reproducible issue! The suggested fix sounds good to me. Would you like to submit a pull request to fix that?