During week 10, our focus was on examining Transformations and Link functions. We delved into these topics using the apartments dataset, which comprises information about apartments in both San Francisco and New York City. Now, let’s analyze and provide feedback on our exploration of these concepts.

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
library(ggrepel)
library(broom)
library(lindia)
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## 
## The following object is masked from 'package:dplyr':
## 
##     recode
## 
## The following object is masked from 'package:purrr':
## 
##     some

Transformations

Below, we upload the dataset and build a linear regression model.

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.
model <- lm(price ~ price_per_sqft,
            filter(apts, in_sf == 0))

rsquared <- summary(model)$r.squared

apts |> 
  filter(in_sf == 0) |>
  ggplot(mapping = aes(x = price_per_sqft, 
                       y = price)) +
  geom_point() +
  geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed', 
              se = FALSE) +
  geom_smooth(se = FALSE) +
  labs(title = "Price vs. Price Per Sq. Ft.",
       subtitle = paste("Linear Fit R-Squared =", round(rsquared, 3))) +
  theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

There are some notable concerns about the model that need addressing. Firstly, the choice of predictors, specifically using price per square foot as a predictor for price, poses a problem. This decision creates a built-in dependency, which goes against the assumption of independence in the model. Moreover, the model appears to overlook potentially influential predictors like neighborhood, number of bedrooms/bathrooms, and building amenities, raising the possibility of introducing bias into the results. The absence of randomization in the data also leaves room for underlying confounding factors that could impact the observed relationship between price and price per square foot.

Additionally, the exclusive reliance on R-squared as the sole metric for evaluating the model is a limitation. This approach provides a narrow perspective on model performance. Considering alternative metrics such as Mean Squared Error or Root Mean Squared Error could offer a more comprehensive assessment of predictive performance. Below is the modified code, now incorporating Mean Squared Error.

# Fit linear regression model
model <- lm(price ~ price_per_sqft, data = filter(apts, in_sf == 0))

# Make predictions
predictions <- predict(model, newdata = filter(apts, in_sf == 0))

# Calculate Mean Squared Error
mse <- mean((apts %>% filter(in_sf == 0) %>% pull(price) - predictions)^2)

# Visualize the data and linear fit
apts %>%
  filter(in_sf == 0) %>%
  ggplot(mapping = aes(x = price_per_sqft, y = price)) +
  geom_point() +
  geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed', se = FALSE) +
  geom_smooth(se = FALSE) +
  labs(
    title = "Price vs. Price Per Sq. Ft.",
    subtitle = paste("Linear Fit MSE =", round(mse, 3))
  ) +
  theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

R-squared primarily emphasizes capturing the variability in the dependent variable, while Mean Squared Error (MSE) directly evaluates prediction accuracy by measuring the average squared differences, offering a more detailed understanding of the model’s effectiveness.

Power transformation

In power transformations, although new linear models were applied following the transformation, a direct comparison with the original model was not conducted. It would have been beneficial to incorporate a few lines of code to formally evaluate and compare the models, determining whether the power-transformed model yields a superior fit.

# Original Model
original_model <- lm(price ~ price_per_sqft, data = filter(apts, in_sf == 0))

# Transformed Model
apts <- apts %>%
  mutate(log_price = log(price))

transformed_model <- lm(log_price ~ price_per_sqft, data = filter(apts, in_sf == 0))

# Model Comparison
summary(original_model)
## 
## Call:
## lm(formula = price ~ price_per_sqft, data = filter(apts, in_sf == 
##     0))
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -4289426 -1480152    19921   894222 17184132 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    -3213431.7   322193.0  -9.974   <2e-16 ***
## price_per_sqft     3689.5      175.8  20.984   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2221000 on 222 degrees of freedom
## Multiple R-squared:  0.6648, Adjusted R-squared:  0.6633 
## F-statistic: 440.3 on 1 and 222 DF,  p-value: < 2.2e-16
summary(transformed_model)
## 
## Call:
## lm(formula = log_price ~ price_per_sqft, data = filter(apts, 
##     in_sf == 0))
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -1.1514 -0.3639 -0.0443  0.3023  1.9612 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    1.271e+01  7.256e-02  175.14   <2e-16 ***
## price_per_sqft 9.815e-04  3.960e-05   24.79   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.5001 on 222 degrees of freedom
## Multiple R-squared:  0.7346, Adjusted R-squared:  0.7334 
## F-statistic: 614.5 on 1 and 222 DF,  p-value: < 2.2e-16
# AIC Comparison
AIC(original_model)
## [1] 7186.49
AIC(transformed_model)
## [1] 329.266

The updated code incorporates explicit model comparison by computing and displaying AIC values for both the original and transformed models. AIC serves as a quantitative measure, offering a more informed evaluation of model performance and complexity. Optimal models exhibit lower AIC values, indicating a favorable balance between fit quality and simplicity. The transformed model demonstrates a significantly reduced AIC compared to the original, implying superior data fit. Unlike the previous reliance on visual assessments and R-squared values, this enhancement introduces AIC—a widely acknowledged metric—improving the precision of model evaluations by considering both fit accuracy and model intricacy.