This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
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
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.
The use of price as the dependent variable while using price per square foot as a predictor creates a problematic dependency, violating the assumption of independence. This is because price is inherently included in the calculation of price per square foot.
Additionally, the model neglects important predictors of price, such as neighborhood, bedroom/bathroom count, and building amenities, which could introduce bias into the results. Moreover, the lack of randomization in the data raises concerns about underlying confounding factors influencing the observed relationship between price and price per square foot.
Interpreting the results reveals limited explanatory power, as indicated by the R-squared value, suggesting that a significant portion of the variation in price remains unexplained. Causation cannot be inferred from this observational data, given the likely interconnected nature of factors influencing both price and price per square foot.
The analysis is further limited by the restriction of the dataset to NYC apartments, which increases consistency but limits generalizability.
# Model price per sqft as a function of price
model <- lm(price_per_sqft ~ price,
filter(apts, in_sf == 0))
# Calculate R-squared
r_squared <- summary(model)$r.squared
# Plot relationship
apts |>
filter(in_sf == 0) |>
ggplot(aes(x = price, y = price_per_sqft)) +
geom_point() +
geom_smooth(method = 'lm', color = 'red', linetype = 'dashed', se = FALSE) +
geom_smooth(color = 'blue', se = FALSE) +
labs(
title = "Price per Sq Ft vs Price for Apartments",
subtitle = sprintf("R-squared: %.3f", r_squared)
) +
theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
It makes more sense to predict price per square foot based on price because price per square foot is inherently determined by price. This approach is consistent with the principle of predicting the less variable factor from the more stable one.
Predicting price per square foot is useful because it allows us to estimate square footage based on a known budget. Additionally, simplifying the code by using a single filter for the relevant condition makes it clearer and less redundant.
Using sprintf() for string formatting instead of paste() makes the code cleaner and easier to read. The revised plot title provides a quick summary of the relationship shown in the visual, and the well-crafted labels make the presentation more user-friendly and informative.
# Add squared price per sqft as a new predictor
apts <- apts |>
mutate(price_per_sqft_squared = price_per_sqft^2)
# Model price using both original and squared price per sqft
model <- lm(price ~ price_per_sqft_squared + price_per_sqft,
filter(apts, in_sf == 0))
# Calculate R squared
r_squared <- summary(model)$r.squared
# Plot the relationship
apts |>
filter(in_sf == 0) |>
ggplot(aes(x = price_per_sqft_squared, y = price)) +
geom_point() +
geom_smooth(method = 'lm', color = 'blue', linetype = 'dashed', se = FALSE) +
geom_smooth(color = 'red', se = FALSE) +
labs(
title = "Price vs Squared Price per Sq Ft for Apts",
x = "Price per Sq Ft Squared",
y = "Price",
subtitle = sprintf("R-squared: %.3f", r_squared)
) +
theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'
Combining filter calls for the same condition eliminates redundancy, making the code more concise and easier to understand. Clear axis labels on the plot provide context for the data represented on both the x and y axes, improving reader comprehension.
Using sprintf() for the subtitle instead of paste() and substitutions makes the code cleaner. Placing the squared term on the x-axis maintains consistency with the model specification, making the representation of the modeled relationship more transparent.
An informative title clearly summarizes the plot’s key relationship, helping readers understand its purpose and importance. Overall, these enhancements in variable naming, code structure, and plot annotations make the analysis more accessible and interpretable.
The provided code creates a linear regression model to predict price based on price_per_sqft, but only includes observations where in_sf is 0. The gg_diagnose function generates diagnostic plots, and saves the residuals vs. fitted and Q-Q plots to the plots object. The plot_all function then displays these two plots, with a maximum of one plot per page.
To improve the analysis, it may be helpful to log-transform the price variable to address skewness in the data. Additionally, incorporating additional diagnostic plots, such as scale-location, can provide further insights into whether the model meets the assumptions of regression. The filter on in_sf suggests that there may be related samples in the data, which could prompt consideration for separate models or including in_sf as a predictor.
Improvements could also involve adding labels and titles to the plots to make them easier to understand and help readers better understand the performance of the model.
The code uses the powerTransform() function from the car package to determine a suitable power transformation for the linear regression model named model. By specifying family=“bcPower,” the code indicates that it intends to apply a Box-Cox power transformation. The outcome of powerTransform() is saved in the object pT. Accessing pT$lambda retrieves the optimal lambda value, which is 0.05507421 in this case. Utilizing pT$lambda isolates and extracts only the lambda parameter, representing the optimal power transformation for the given model.
The variable ‘price’ is transformed logarithmically to create a new variable named ‘log_price’ in order to address skewness. A linear model is then fitted to predict ‘log_price’ from ‘price_per_sqft’. A filter is applied to only include instances where ‘in_sf’ equals 0. The R-squared value is computed from the model summary. A scatterplot is then generated to depict the relationship between ‘price_per_sqft’ and the logarithm of ‘price’. The plot includes a linear regression line, and custom labels, incorporating the R-squared value, are applied for clarity.
Visualizing the distribution of sqft before and after transformation would show how the transformation affects the distribution. It is suggested to include additional diagnostics, such as residuals vs. fitted values, to check that the smoothing line is accurate. Specify the smoothing line method, whether it’s loess, gam, or another, to make the analysis clearer. Improvements to the plot, such as making the points transparent, grouping them by subsets, or using color to encode a variable, could make it more effective. To make the analysis stronger, consider using model validation techniques like training/test splits to evaluate the model’s performance more rigorously.