library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.0 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.1 ✔ tibble 3.1.8
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(ggthemes)
## Warning: package 'ggthemes' was built under R version 4.2.3
library(ggrepel)
## Warning: package 'ggrepel' was built under R version 4.2.3
library(broom)
library(lindia)
## Warning: package 'lindia' was built under R version 4.2.3
library(car)
## Warning: package 'car' was built under R version 4.2.3
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.2.3
##
## Attaching package: 'car'
##
## The following object is masked from 'package:dplyr':
##
## recode
##
## The following object is masked from 'package:purrr':
##
## some
url <- "https://raw.githubusercontent.com/leontoddjohnson/i590/main/data/apartments/apartments.csv"
apts <- read_delim(url, delim = ',')
## Rows: 492 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (8): in_sf, beds, bath, price, year_built, sqft, price_per_sqft, elevation
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# repeating the transformations
apts <- apts |>
mutate(price_per_sqft_2 = price_per_sqft ^ 2,
log_price = log(price),
sqrt_sqft = sqrt(sqft))
# Explore the relationships between variables
pairs(apts[, c("year_built", "sqft", "elevation", "beds", "log_price")])
# Calculate correlation matrix
cor_matrix <- cor(apts[, c("year_built", "sqft", "elevation", "beds", "log_price")])
print(cor_matrix)
## year_built sqft elevation beds log_price
## year_built 1.00000000 -0.0413914 -0.2089692 -0.07223557 0.2325606
## sqft -0.04139140 1.0000000 0.1746025 0.78850393 0.7434016
## elevation -0.20896922 0.1746025 1.0000000 0.33126732 -0.1478345
## beds -0.07223557 0.7885039 0.3312673 1.00000000 0.5246238
## log_price 0.23256062 0.7434016 -0.1478345 0.52462381 1.0000000
Is this a “good” selection of variables? What could we be missing, or are there potential biases inherent in the groups of apartments here?
A negative correlation of -0.041 indicates a weak negative relationship between the year a property was built and its square footage. This could suggest that older buildings tend to have smaller square footage.
A strong positive correlation of 0.79 indicates a significant positive relationship between square footage and the number of bedrooms. Larger apartments tend to have more bedrooms.
A positive correlation of 0.17 suggests a relatively weak positive relationship between elevation and square footage. This could imply that properties at higher elevations might, on average, have slightly larger square footage.
A moderate positive correlation of 0.52 suggests that the number of bedrooms is positively associated with the logarithm of the price. This indicates that apartments with more bedrooms tend to have higher prices.
A weak negative correlation of -0.15 indicates a slight negative relationship between elevation and the logarithm of the price. This suggests that, on average, apartments at higher elevations might have slightly lower prices.
A strong positive correlation of 0.74 suggests a significant positive relationship between square footage and the logarithm of the price. Larger apartments tend to have higher prices.
Considering the correlations, the selected variables seem reasonable for predicting the logarithm of the price.
Something that we could be missing here is the location of these properties. The location of an apartment can significantly impact its price. Factors like neighborhood, proximity to amenities, and safety can influence housing prices. If location-related variables are not included, it may introduce bias.
Nowhere in the lab do we investigate the assumptions of a linear model. Is the relationship between the response (i.e., \(\log(\text{price})\)) and each of these variables linear? Are the error terms evenly distributed?
# Fit linear models and check assumptions
lm_results <- lm(log_price ~ year_built + sqft + elevation + beds, data = apts)
tidy(lm_results)
## # A tibble: 5 × 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 4.94 1.03 4.77 2.40e- 6
## 2 year_built 0.00428 0.000525 8.16 2.97e-15
## 3 sqft 0.000644 0.0000338 19.1 5.56e-61
## 4 elevation -0.00397 0.000470 -8.45 3.46e-16
## 5 beds -0.0114 0.0274 -0.417 6.77e- 1
# Check linearity assumption by plotting residuals against fitted values
ggplot(lm_results, aes(x = .fitted, y = .resid)) +
geom_point() +
geom_hline(yintercept = 0, linetype = "dashed", color = "red") +
labs(title = "Residuals vs Fitted Values")
# Check distribution of errors
qqnorm(resid(lm_results))
qqline(resid(lm_results))
Since the residuals scattered randomly around the zero line, we can safely assume that there’s a linear relationship between the response variable and each of these variables. Furthermore, the Q-Q plot shows that the error terms are evenly distributed.
Is it possible that our conclusions are more appropriate for some group(s) of the data and not others?
# Evaluate model performance on different subsets (e.g., based on bedrooms)
summary(lm_results)
##
## Call:
## lm(formula = log_price ~ year_built + sqft + elevation + beds,
## data = apts)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.97503 -0.30950 0.02382 0.28651 1.14671
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.936e+00 1.034e+00 4.773 2.40e-06 ***
## year_built 4.283e-03 5.251e-04 8.156 2.97e-15 ***
## sqft 6.443e-04 3.378e-05 19.073 < 2e-16 ***
## elevation -3.968e-03 4.698e-04 -8.447 3.46e-16 ***
## beds -1.142e-02 2.740e-02 -0.417 0.677
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4618 on 487 degrees of freedom
## Multiple R-squared: 0.6765, Adjusted R-squared: 0.6738
## F-statistic: 254.5 on 4 and 487 DF, p-value: < 2.2e-16
# Assess model fit using metrics like R-squared, AIC, BIC
summary(lm_results)$r.squared
## [1] 0.6764511
AIC(lm_results)
## [1] 642.856
BIC(lm_results)
## [1] 668.0469Based on the above summary statistics, it is possible that our conclusions are more appropriate for some groups of the data and not others. For instance, ‘beds’ variable is not statistically significant because of its p-value of 0.677. Meanwhile, all the other variables have a very low p-value < 0.05 so the majority of the data is affecting the response variable.
What if assumptions are not met? What could happen to this model if it were deployed on a platform like Zillow?
If the assumptions of the linear regression model are not met, deploying it on platforms like Zillow could lead to biased parameter estimates, inefficient predictions, incorrect inferences, and the presence of residual patterns. This may result in misrepresentation of underlying patterns, potential misleading conclusions, ethical concerns, and a loss of user trust.
Consider different evaluation metrics between models. What is a practical use for these values?
Different evaluation metrics provide insights into different aspects of a model’s performance. The root mean squared error can provide a measure of the average prediction error, but it gives more weight to larger errors. RMSE could be useful for assessing the overall accuracy of price predictions, with a focus on penalizing larger errors more significantly. Another evaluation metric we could use is R². R² could be employed to evaluate how well the model explains the variability in log prices based on features like square footage, year built, elevation, and the number of bedrooms. A higher R² suggests that a larger proportion of the variability in log prices is accounted for by the model.