1

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!

Vy Nguyen
  • 11
  • 4
  • Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Nov 14 '18 at 16:13
  • Hope you have heard of ggResidpanel https://goodekat.github.io/ggResidpanel-tutorial/tutorial.html. – hnguyen Nov 18 '20 at 19:44

1 Answers1

1

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")
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • happy to try to improve this if there is a stated reason for the downvote ... – Ben Bolker Apr 12 '20 at 22:59
  • 1
    I only see a missing bracket here ` y=residuals(fit_num_var))` which could have been `y=residuals(fit_num_var)))`. Thank you so much for the code. – hnguyen Nov 18 '20 at 19:41