Create a new section after we predict final stores
In this section, we're going to create a new model function. This model function will not delete variables with high VIF. Instead, it'll automatically figure out what variables it should try to combine based on their correlation, including the original variables, the custom ones, and the per capita ones.
It'll need to figure out how to get all the variable names from both datasets even if they are of different sizes. It needs to run totally automatically when the code is run. If making it an iterative process is better (printing the summary of each new model), we can do that. Keep it all in it's own section
Then create a new section under that new model section. This section will go through the original store prediction process but for the new store model
You can just give me the new sections that go at the bottom of the code instead of returning the full code.
Code:
Load required packages
library(car) # For VIF
library(dplyr) # For data manipulation
library(corrplot) # For correlation plot
library(moments) # For skewness calculation
vif_values_filtered_custom <- vif(model_vif_filtered_custom)
print("VIF Values after filtering:")
print(vif_values_filtered_custom)
Remove insignificant variables based on p-values
coeff_summary_custom <- summary(model_vif_filtered_custom)$coefficients
high_pval_vars_custom <- rownames(coeff_summary_custom)[coeff_summary_custom[, "Pr(>|t|)"] > 0.1]
high_pval_vars_custom <- setdiff(high_pval_vars_custom, "(Intercept)")
print("Variables with p-value > 0.1 to be considered for removal:")
print(high_pval_vars_custom)
if("EMPL" %in% names(df)) {
# Convert EMPL to numeric, keeping original values
dfEMPL<−as.numeric(as.character(dfEMPL))
code
if(is_training) {
# Store mean EMPL from training data for later use
assign("mean_empl", mean(df$EMPL, na.rm = TRUE), envir = .GlobalEnv)
} else {
# Use stored mean from training data
if(exists("mean_empl")) {
df$EMPL[is.na(df$EMPL)] <- mean_empl
}
}
}
2. Create derived variables
df <- create_variables(df) # Your existing create_variables function
3. Handle infinite and NA values for all numeric columns
numeric_cols <- sapply(df, is.numeric)
for(col in names(df)[numeric_cols]) {
# Replace infinite values with NA
df[[col]][is.infinite(df[[col]])] <- NA
code
# Handle NA values
if(any(is.na(df[[col]]))) {
if(is_training) {
# Store mean for each column from training data
assign(paste0("mean_", col), mean(df[[col]], na.rm = TRUE), envir = .GlobalEnv)
df[[col]][is.na(df[[col]])] <- get(paste0("mean_", col))
} else {
# Use stored means from training data
if(exists(paste0("mean_", col))) {
df[[col]][is.na(df[[col]])] <- get(paste0("mean_", col))
}
}
}
}
return(df)
}
Apply the new preparation function to both datasets
View predicted performance ratios for validation stores
print("Predicted Performance Ratios for the 10 stores:")
print(CroqPainFix_10[, c("STOR", "Predicted_EARN", "K", "Performance_Ratio")])
Determine which stores meet the performance ratio target of 26%
stores_to_open_custom <- subset(CroqPainFix_10, Performance_Ratio >= 26)
print("Stores to consider opening based on predicted performance ratio >= 26%:")
print(stores_to_open_custom[, c("STOR", "Performance_Ratio")])
Final Prediction
Convert STOR to character if needed in CroqPain_new
View predicted performance ratios for new locations
print("Predicted Performance Ratios for the new locations:")
print(CroqPain_new[, c("STOR", "Predicted_EARN", "K", "Performance_Ratio")])
Recommend which locations to open based on performance ratio target of 26%
locations_to_open_custom <- subset(CroqPain_new, Performance_Ratio >= 26)
print("Recommended locations to open (Performance Ratio >= 26%):")
print(locations_to_open_custom[, c("STOR", "Performance_Ratio")])
}, error = function(e) {
print("Error in prediction:")
print(e)
Print the structure of both datasets for debugging
print("Structure of model variables:")
print(str(CroqPainFix[, model_vars]))
print("Structure of prediction variables:")
print(str(CroqPain_new[, model_vars]))
})
Here are the two new sections to add at the bottom of your code:
First Section: New Model Building by Combining Highly Correlated Variables
R
# *********************************************************
# New Model Building Section: Combining Highly Correlated Variables
# *********************************************************
# Initialize variables
corr_threshold <- 0.8 # Correlation threshold for combining variables
variables <- names(CroqPainFix)
# Select numeric predictor variables, excluding the response variable
numeric_vars <- names(CroqPainFix)[sapply(CroqPainFix, is.numeric)]
numeric_vars <- setdiff(numeric_vars, 'EARN')
# Create a copy of the data to work on
data_for_model <- CroqPainFix[, c('EARN', numeric_vars)]
# Initialize variable list for the model
model_vars <- numeric_vars
# Initialize a list to keep track of combined variables
combination_list <- list()
# Initialize the loop flag
correlation_loop <- TRUE
while (correlation_loop) {
# Compute correlation matrix among predictor variables
cor_matrix <- cor(data_for_model[, model_vars], use = "complete.obs")
# Set diagonal to zero to avoid self-correlation
diag(cor_matrix) <- 0
# Find the pair of variables with the highest absolute correlation
max_corr <- max(abs(cor_matrix))
if (max_corr > corr_threshold) {
# Find the indices of the variables with the highest correlation
high_corr_indices <- which(abs(cor_matrix) == max_corr, arr.ind = TRUE)[1, ]
var1 <- model_vars[high_corr_indices[1]]
var2 <- model_vars[high_corr_indices[2]]
cat("Combining variables:", var1, "and", var2, "with correlation", max_corr, "\n")
# Create new variable name
new_var_name <- paste(var1, var2, sep = "_")
# Create the new variable as the average of the two variables
data_for_model[[new_var_name]] <- (data_for_model[[var1]] + data_for_model[[var2]]) / 2
# Remove the original variables from model_vars
model_vars <- setdiff(model_vars, c(var1, var2))
# Add the new variable to model_vars
model_vars <- c(model_vars, new_var_name)
# Keep track of the combination
combination_list[[new_var_name]] <- c(var1, var2)
} else {
# No pair exceeds the threshold
correlation_loop <- FALSE
}
}
# Build the new model with the combined variables
new_model_formula <- as.formula(paste("EARN ~", paste(model_vars, collapse = " + ")))
new_model <- lm(new_model_formula, data = data_for_model)
# Check summary of the new model
summary(new_model)
# Check VIF to confirm multicollinearity reduction
vif_new_model <- vif(new_model)
print("VIF Values of the new model:")
print(vif_new_model)
Second Section: Prediction Using the New Model
R
# *********************************************************
# Prediction Using New Model
# *********************************************************
# Prepare CroqPain_new data
# Ensure all required variables are present and processed
CroqPain_new <- prepare_data(CroqPain_new, is_training = FALSE)
# Apply the same variable combinations to CroqPain_new
for (new_var_name in names(combination_list)) {
vars_to_combine <- combination_list[[new_var_name]]
# Check if both variables are present in CroqPain_new
if (all(vars_to_combine %in% names(CroqPain_new))) {
CroqPain_new[[new_var_name]] <- (CroqPain_new[[vars_to_combine[1]]] + CroqPain_new[[vars_to_combine[2]]]) / 2
} else {
cat("Variables", vars_to_combine, "not found in CroqPain_new. Cannot create", new_var_name, "\n")
}
}
# Build the dataset for prediction
prediction_vars <- model_vars # The variables in the new model
# Ensure all required variables are present in CroqPain_new
missing_vars <- setdiff(prediction_vars, names(CroqPain_new))
if (length(missing_vars) > 0) {
cat("The following variables are missing in CroqPain_new and will be set to 0:", missing_vars, "\n")
for (var in missing_vars) {
CroqPain_new[[var]] <- 0 # Or handle appropriately
}
}
# Make predictions using the new model
predictions_new <- predict(new_model, newdata = CroqPain_new)
# Add predictions to CroqPain_new
CroqPain_new$Predicted_EARN <- predictions_new
CroqPain_new$Performance_Ratio <- CroqPain_new$Predicted_EARN / CroqPain_new$K * 100
# View predicted performance ratios for new locations
print("Predicted Performance Ratios for the new locations using new model:")
print(CroqPain_new[, c("STOR", "Predicted_EARN", "K", "Performance_Ratio")])
# Recommend which locations to open based on performance ratio target of 26%
locations_to_open_new_model <- subset(CroqPain_new, Performance_Ratio >= 26)
print("Recommended locations to open (Performance Ratio >= 26%) using new model:")
print(locations_to_open_new_model[, c("STOR", "Performance_Ratio")])
Explanation:
First Section:
Purpose: Build a new linear regression model by automatically combining highly correlated variables instead of deleting them.
Process:
Compute the correlation matrix of all numeric predictor variables.
Iteratively identify pairs of variables with absolute correlation above the threshold (0.8 in this case).
For each such pair, create a new variable by averaging the two variables.
Remove the original variables from the model variables list and add the new combined variable.
Repeat the process until there are no variable pairs with correlation above the threshold.
Build the final model using the combined variables.
Check the model summary and VIF values to ensure multicollinearity has been reduced.
Second Section:
Purpose: Use the new model to predict the performance of new stores, following the original prediction process.
Process:
Prepare the new data (CroqPain_new) using the prepare_data function to ensure consistency.
Apply the same variable combinations to the new data as were applied during model building.
Ensure all required variables are present in the new data.
Make predictions using the new model.
Calculate the performance ratio and determine which stores meet the performance target.
Output the predictions and recommendations.
Note:
The code is designed to run automatically, handling variable names dynamically even if the datasets vary in size.
Variables are combined based on their correlation without manual intervention.
The process includes detailed comments and prints to help in tracking the procedure's progress during execution.