# Load required packages
library(car) # For VIF
library(dplyr) # For data manipulation
library(corrplot) # For correlation plot
library(leaps) # For variable selection (if needed)
# Load the data
load("C:/Users/kylek/OneDrive/Desktop/Stats 2/CroqPain_new.rda")
load("C:/Users/kylek/OneDrive/Desktop/Stats 2/CroqPainFix.rda")
# Ensure data frames are correctly named
CroqPainFix <- CroqPainFix
CroqPain_new <- CroqPain_new
# Convert STOR in CroqPainFix to character (if needed)
CroqPainFix$STOR <- as.character(CroqPainFix$STOR)
# Convert EMPL in CroqPain_new to integer
CroqPain_new$EMPL <- as.integer(as.character(CroqPain_new$EMPL))
# Handle NA values in EMPL in CroqPain_new by replacing with mean
CroqPain_new$EMPL[is.na(CroqPain_new$EMPL)] <- mean(CroqPain_new$EMPL, na.rm = TRUE)
# Part 2-1: Building Models (Part a)
# =============================================
# Step 1: Explore the data
# View structure of CroqPainFix
str(CroqPainFix)
# Summary statistics
summary(CroqPainFix)
# Check for missing values
colSums(is.na(CroqPainFix))
# Step 2: Examine correlations among variables
# Select numeric variables for correlation analysis
numeric_vars <- sapply(CroqPainFix, is.numeric)
cor_matrix <- cor(CroqPainFix[, numeric_vars], use = "complete.obs")
# Visualize correlation matrix
corrplot(cor_matrix, method = "circle", tl.cex = 0.7)
# Step 3: Build initial regression model with all potential explanatory variables
# Define the formula with all variables (adjust variable names as per your dataset)
initial_formula <- EARN ~ SIZE + EMPL + total + P15 + P25 + P35 + P45 + P55 +
INC + COMP + NCOMP + NREST + PRICE + CLI
# Fit the initial model
model_initial <- lm(initial_formula, data = CroqPainFix)
# Check summary of the initial model
summary(model_initial)
# Step 4: Check for multicollinearity using VIF
vif_values <- vif(model_initial)
print("VIF Values:")
print(vif_values)
# Identify variables with VIF > 5
high_vif <- vif_values[vif_values > 5]
print("Variables with VIF > 5:")
print(high_vif)
# Step 5: Iteratively remove variables with high VIF
# Function to iteratively remove variables with highest VIF
remove_high_vif <- function(model, threshold = 5) {
vif_values <- vif(model)
max_vif <- max(vif_values)
while (max_vif > threshold) {
var_to_remove <- names(which.max(vif_values))
cat("Removing variable due to high VIF:", var_to_remove, "\n")
# Update the formula
formula_terms <- attr(terms(model), "term.labels")
formula_terms <- setdiff(formula_terms, var_to_remove)
new_formula <- as.formula(paste("EARN ~", paste(formula_terms, collapse = " + ")))
# Refit the model
model <- lm(new_formula, data = CroqPainFix)
vif_values <- vif(model)
max_vif <- max(vif_values)
}
return(model)
}
# Apply the function to remove high VIF variables
model_vif_filtered <- remove_high_vif(model_initial, threshold = 5)
# Check summary of the model after VIF filtering
summary(model_vif_filtered)
# Check VIFs after filtering
vif_values_filtered <- vif(model_vif_filtered)
print("VIF Values after filtering:")
print(vif_values_filtered)
# Step 6: Remove insignificant variables based on p-values
# Identify variables with p-value > 0.1
coeff_summary <- summary(model_vif_filtered)$coefficients
high_pval_vars <- rownames(coeff_summary)[coeff_summary[, "Pr(>|t|)"] > 0.1]
# Exclude Intercept
high_pval_vars <- setdiff(high_pval_vars, "(Intercept)")
print("Variables with p-value > 0.1 to be considered for removal:")
print(high_pval_vars)
# Remove variables with high p-values
final_terms <- attr(terms(model_vif_filtered), "term.labels")
final_terms <- setdiff(final_terms, high_pval_vars)
final_formula <- as.formula(paste("EARN ~", paste(final_terms, collapse = " + ")))
# Fit the final model
model_final <- lm(final_formula, data = CroqPainFix)
# Summary of the final model
summary(model_final)
# Check VIFs of the final model
vif_final <- vif(model_final)
print("Final model VIF values:")
print(vif_final)
# Step 7: Diagnostic plots for the final model
par(mfrow = c(2, 2))
plot(model_final)
# Reset plotting layout
par(mfrow = c(1, 1))
# Check normality of residuals with Q-Q plot
qqnorm(resid(model_final))
qqline(resid(model_final))
# Decision on explanatory variables:
# The final model includes variables with significant coefficients and acceptable VIF values,
# thus addressing multicollinearity and improving model reliability.
# 2-2. Validation by Testing (Part b)
# =============================================
# Split the data into CroqPainFix_50 and CroqPainFix_10
CroqPainFix$STOR <- as.integer(CroqPainFix$STOR) # Ensure STOR is integer for comparison
CroqPainFix_50 <- subset(CroqPainFix, STOR <= 50)
CroqPainFix_10 <- subset(CroqPainFix, STOR > 50)
# Re-estimate the final model using CroqPainFix_50
model_final_50 <- lm(formula(model_final), data = CroqPainFix_50)
# Predict the performances of the 10 stores in CroqPainFix_10
predictions_10 <- predict(model_final_50, newdata = CroqPainFix_10)
# Add predictions to CroqPainFix_10
CroqPainFix_10$Predicted_EARN <- predictions_10
# Calculate predicted performance ratio
# Assuming performance ratio is EARN / K (investment)
CroqPainFix_10$Performance_Ratio <- CroqPainFix_10$Predicted_EARN / CroqPainFix_10$K * 100 # in percentage
# View predicted performance ratios
print("Predicted Performance Ratios for the 10 stores:")
CroqPainFix_10[, c("STOR", "Predicted_EARN", "K", "Performance_Ratio")]
# Determine which stores meet the performance ratio target of 26%
stores_to_open <- subset(CroqPainFix_10, Performance_Ratio >= 26)
print("Stores to consider opening based on predicted performance ratio >= 26%:")
stores_to_open[, c("STOR", "Performance_Ratio")]
# 3. Prediction (Part c)
# =============================================
# Use the complete model (from CroqPainFix) to predict new locations
# Ensure CroqPain_new has the same variable structure and types
# If necessary, convert or create any missing variables
# Convert STOR to character if needed
CroqPain_new$STOR <- as.character(CroqPain_new$STOR)
# Replace any missing EMPL values with mean (already done earlier)
# Ensure all required variables are present
required_vars <- all.vars(formula(model_final))
missing_vars <- setdiff(required_vars, names(CroqPain_new))
if (length(missing_vars) > 0) {
stop("The following variables are missing in CroqPain_new: ", paste(missing_vars, collapse = ", "))
}
# Predict performance for new locations
predictions_new <- predict(model_final, newdata = CroqPain_new)
# Add predictions to CroqPain_new
CroqPain_new$Predicted_EARN <- predictions_new
# Calculate predicted performance ratio
# Assuming performance ratio is EARN / K (investment)
CroqPain_new$Performance_Ratio <- CroqPain_new$Predicted_EARN / CroqPain_new$K * 100 # in percentage
# View predicted performance ratios
print("Predicted Performance Ratios for the new locations:")
CroqPain_new[, c("STOR", "Predicted_EARN", "K", "Performance_Ratio")]
# Recommend which locations to open based on performance ratio target of 26%
locations_to_open <- subset(CroqPain_new, Performance_Ratio >= 26)
print("Recommended locations to open (Performance Ratio >= 26%):")
locations_to_open[, c("STOR", "Performance_Ratio")]
Explanation:
Part 2-1 (Building Models):
-
Data Preparation: We load the data and ensure that all variables are of the correct type. Missing values are handled appropriately.
-
Exploratory Data Analysis: We examine the structure and summary of the data and calculate the correlation matrix to understand relationships between variables.
-
Multicollinearity Check: Using the Variance Inflation Factor (VIF), we identify variables that cause multicollinearity (VIF > 5) and iteratively remove them, starting with the one with the highest VIF.
-
Model Refinement: After addressing multicollinearity, we examine the p-values of the remaining variables and remove those that are not statistically significant (p-value > 0.1).
-
Final Model: We obtain a model that includes only significant variables with acceptable VIF values, ensuring that none of the basic regression assumptions are violated and that the model has good predictive power.
Part 2-2 (Validation by Testing):
-
Data Splitting: We split the original data into two subsets: CroqPainFix_50 (stores with STOR <= 50) and CroqPainFix_10 (stores with STOR > 50).
-
Model Re-estimation: We re-estimate the final model using CroqPainFix_50.
-
Prediction: Using this model, we predict the performances (EARN) of the 10 stores in CroqPainFix_10 and compute their predicted performance ratios.
-
Decision Making: We compare the predicted performance ratios to the target of 26% and identify which stores meet or exceed this threshold, indicating they should have been opened.
Part 3 (Prediction):
-
New Data Preparation: We ensure that the CroqPain_new dataset has all the necessary variables required by the final model.
-
Prediction: Using the final model (built on the complete CroqPainFix dataset), we predict the performance of the new potential locations.
-
Recommendation: We calculate the predicted performance ratios for these locations and recommend opening the ones with a performance ratio of at least 26%.
Note: Adjust variable names and data paths according to your actual data. Ensure that all variables required by the model are present in the new datasets and handle any discrepancies appropriately. The performance ratio calculation assumes that EARN represents earnings and K represents the investment for each store.