library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.3 ✔ 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(AmesHousing)
library(boot)
library(broom)
Share your model critique in this notebook as your data dive submission for the week.**
As a start, think about the context of the lab and consider the following:
Analytical issues, such as model assumptions
Overcoming biases (existing or potential)
Possible risks or societal implications
Crucial issues which might not be measurable
Is this a “good” selection of variables? What could we be missing, or are there potential biases inherent in the groups of apartments here?
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?
Is it possible that our conclusions are more appropriate for some group(s) of the data and not others?
What if assumptions are not met? What could happen to this model if it were deployed on a platform like Zillow?
In week 8 we learned about the Linear Regresstion, linear regression is a statistical method used for modeling the relationship between a dependent variable and one or more independent variables. The relationship is modeled as a linear equation, where the coefficients represent the slope and intercept of the line.
In this lab the analytical issues, such as model assumptions are when performing ANOVA (Analysis of Variance) or regression analysis. There are several assumptions that need to be validated before interpreting the results of these models. Two common assumptions are normality and homoscedasticity.
In this example, we assume we are predicting house prices (SalePrice) based on two independent variables (GrLivArea and OverallQual). The code then checks the normality assumption using a histogram, Q-Q plot, and Shapiro-Wilk test on the residuals. For homoscedasticity, it utilizes the residuals vs. fitted values plot, the scale-location plot, and Levene’s test.
# make a simpler name for (and a copy of) the Ames data
ames <- make_ames()
ames <- ames |> rename_with(tolower)
ames_dataanalyssis<-ames
print(ames_dataanalyssis)
## # A tibble: 2,930 × 81
## ms_subclass ms_zoning lot_frontage lot_area street alley lot_shape
## <fct> <fct> <dbl> <int> <fct> <fct> <fct>
## 1 One_Story_1946_and_Ne… Resident… 141 31770 Pave No_A… Slightly…
## 2 One_Story_1946_and_Ne… Resident… 80 11622 Pave No_A… Regular
## 3 One_Story_1946_and_Ne… Resident… 81 14267 Pave No_A… Slightly…
## 4 One_Story_1946_and_Ne… Resident… 93 11160 Pave No_A… Regular
## 5 Two_Story_1946_and_Ne… Resident… 74 13830 Pave No_A… Slightly…
## 6 Two_Story_1946_and_Ne… Resident… 78 9978 Pave No_A… Slightly…
## 7 One_Story_PUD_1946_an… Resident… 41 4920 Pave No_A… Regular
## 8 One_Story_PUD_1946_an… Resident… 43 5005 Pave No_A… Slightly…
## 9 One_Story_PUD_1946_an… Resident… 39 5389 Pave No_A… Slightly…
## 10 Two_Story_1946_and_Ne… Resident… 60 7500 Pave No_A… Regular
## # ℹ 2,920 more rows
## # ℹ 74 more variables: land_contour <fct>, utilities <fct>, lot_config <fct>,
## # land_slope <fct>, neighborhood <fct>, condition_1 <fct>, condition_2 <fct>,
## # bldg_type <fct>, house_style <fct>, overall_qual <fct>, overall_cond <fct>,
## # year_built <int>, year_remod_add <int>, roof_style <fct>, roof_matl <fct>,
## # exterior_1st <fct>, exterior_2nd <fct>, mas_vnr_type <fct>,
## # mas_vnr_area <dbl>, exter_qual <fct>, exter_cond <fct>, foundation <fct>, …
view(ames)
# Fit a linear regression model
lm_model <- lm(sale_price~ gr_liv_area + overall_qual, data = ames)
# Check assumptions
# Normality Assumption
# Histogram of Residuals
hist(residuals(lm_model), main = "Histogram of Residuals", col = "lightblue", border = "black")
# Q-Q Plot
qqnorm(residuals(lm_model))
qqline(residuals(lm_model), col = 2)
# Shapiro-Wilk Test for Normality
shapiro.test(residuals(lm_model))
##
## Shapiro-Wilk normality test
##
## data: residuals(lm_model)
## W = 0.88695, p-value < 2.2e-16
# Homoscedasticity Assumption
# Residuals vs. Fitted Values Plot
plot(lm_model, which = 1)
# Scale-Location Plot
plot(sqrt(abs(resid(lm_model))) ~ fitted(lm_model), ylab = "Sqrt(|Residuals|)", xlab = "Fitted Values", main = "Scale-Location Plot")
Suggestion: Multiple Hypothesis Testing (to make more robust and reliable model), this mitigates potential Type I Error (False Positive) and bias
Type I Error (False Positive): Type I error occurs when a null hypothesis that is actually true is incorrectly rejected. In the context of multiple hypothesis testing, if you perform several hypothesis tests without adjusting for multiple comparisons, the probability of encountering at least one false positive (rejecting a true null hypothesis) by chance increases.
Bias Mitigation Impact: By using methods like Tukey’s HSD test or controlling FDR, you reduce the probability of erroneously concluding that there is a significant difference or relationship when, in reality, there isn’t. These methods help maintain a balance between identifying true effects and minimizing the risk of falsely detecting effects due to multiple testing. They provide more stringent control over Type I errors and, in the case of FDR control, allow for a higher power to detect true effects among multiple tests. In summary, the bias mitigated here primarily involves lowering the probability of falsely identifying relationships or differences between groups when conducting.
# Performing ANOVA
m <- aov(sale_price ~ bldg_type, data = ames)
summary(m)
## Df Sum Sq Mean Sq F value Pr(>F)
## bldg_type 4 6.454e+11 1.614e+11 26.15 <2e-16 ***
## Residuals 2925 1.805e+13 6.170e+09
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Run the p.adjust function
#adjusted_p_values <- p.adjust(p_values, method = "BH")
# Display adjusted p-values
#print(adjusted_p_values)
# Display summary statistics of adjusted p-values
#summary(adjusted_p_values)
# Assuming you've already run the Tukey HSD test
tukey_results <- TukeyHSD(m)
# Print the complete Tukey HSD results
print(tukey_results)
## Tukey multiple comparisons of means
## 95% family-wise confidence level
##
## Fit: aov(formula = sale_price ~ bldg_type, data = ames)
##
## $bldg_type
## diff lwr upr p adj
## TwoFmCon-OneFam -59230.332 -86804.779 -31655.88 0.0000000
## Duplex-OneFam -45003.105 -65995.154 -24011.06 0.0000001
## Twnhs-OneFam -48877.982 -70651.106 -27104.86 0.0000000
## TwnhsE-OneFam 7499.873 -7205.102 22204.85 0.6328136
## Duplex-TwoFmCon 14227.226 -19877.110 48331.56 0.7859640
## Twnhs-TwoFmCon 10352.350 -24238.235 44942.93 0.9255215
## TwnhsE-TwoFmCon 66730.204 36092.386 97368.02 0.0000000
## Twnhs-Duplex -3874.876 -33486.100 25736.35 0.9965227
## TwnhsE-Duplex 52502.978 27623.431 77382.53 0.0000001
## TwnhsE-Twnhs 56377.855 30835.836 81919.87 0.0000000
In the context of “Lab 8” code discussing ANOVA, Linear Regression, and Simpson’s Paradox, there are several crucial issues that might not be directly measurable due to certain inherent limitations or complexities within the statistical analysis process. These issues can affect the reliability or generalizability of the conclusions drawn from the analyses. Some of these crucial issues include:
Causality vs. Correlation: Statistical analyses, especially those involving observational data, might establish correlations between variables but not necessarily indicate causality. Determining causality often requires additional evidence, such as controlled experiments, to ascertain a cause-and-effect relationship. For instance, while regression analysis might show a relationship between certain house features and sale prices, it may not definitively prove that these features directly cause changes in prices.
Linear Regression: Provides an introduction to linear regression using Anscombe’s Quartet and further extends it to cover single-variable and multiple-variable regression, interaction terms, multicollinearity, errors, and diagnostics.
Multicollinearity : Multicollinearity occurs when predictor variables in a regression model are highly correlated with each other. This can cause issues in interpreting the significance of individual predictors.
Simpson’s Paradox and Misleading Aggregations: Simpson’s Paradox refers to a phenomenon where trends or associations observed in different groups vanish or even reverse when the groups are aggregated. It is a statistical paradox that might not be immediately apparent and might mislead the interpretation of the overall relationship between variables.
These issues might not be directly measurable due to their nature, complexity, or the limitations of the available data. While statistical techniques aim to mitigate these issues, certain challenges remain, and addressing these challenges often requires a deeper understanding of the data context, subject matter expertise, and careful consideration of potential biases and limitations within the analysis.