Vy Nguyen
Vy Nguyen

Reputation: 11

How to plot studentized residuals and fitted values in R using ggplot?

First, I fitted the model from my data in clean_sales and passed it on an object fit_num_var, but then I had difficulty making it into a plot to visualize the fitted values and the studentized residuals. My code is below:

#Outliers 
attach(clean_sales)
fit_num_var <- lm(SalePrice ~ ResidentialUnits + CommercialUnits + 
                  YearBuilt + TotalUnits + LandSquareFeet + GrossSquareFeet)
fit_num_var
ggplot(fit_num_var, aes(x=as.vector(fitted.values), y=as.vector(residuals))) + 
geom_point() + geom_line() + xlab("Fitted Values") + ylab("Studentized Residuals")

The error message was:

Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'

Please let me know how I should fix this. Thanks a lot!

Upvotes: 1

Views: 2662

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226577

No reproducible example, but try this:

  • don't use attach(), use the data= argument to lm() instead (this isn't your actual problem, but is better practice)
  • use fitted(fit_num_var), etc.
  • you might also be interested in the augment function from the broom package
fit_num_var <- lm(SalePrice ~ ResidentialUnits + CommercialUnits + 
              YearBuilt + TotalUnits + LandSquareFeet + GrossSquareFeet,
   data=clean_sales)
ggplot(fit_num_var, aes(x=fitted(fit_num_var), 
          y=residuals(fit_num_var))) + 
         geom_point() + smooth() + xlab("Fitted Values") + 
                                   ylab("Studentized Residuals")

Upvotes: 1

Related Questions