install.packages(olsrr) library(tidyverse) library(olsrr)

General Idea of the data

summary(Walmart)

set.seed(123)

Splitting data into training and validation

temp0 <- Walmart %>% mutate(random = runif(6435) , Store = as.factor(Store) , Holiday_Flag = as.factor(Holiday_Flag))

summary(temp0) str(temp0)

hist(temp0\(random) summary(temp0\)random)

trainlm <- temp0 %>% filter(random < 0.7) %>% select(-random)

validationlm <- temp0 %>% filter(random >= 0.7) %>% select(-random)

Creating Linear Model

model1 <- lm(Weekly_Sales ~ .-Date , data = trainlm)

Checking results

summary(model1)

Now creating a model with backward selection

bckwd <- ols_step_backward_p(model1 , details = T , prem = 0.01) model2 <- bckwd$model1 summary(model2)

Creating a model with Interations

model3 <- lm(Weekly_Sales ~ (.-Date)^2 , data = trainlm) summary(model3)

Now doing the backward selection process on the model with interactions

bckwd2 <- ols_step_backward_p(model3 , details = T , prem = 0.01) model4 <- bckwd2$model summary(model4)

Scoring the validation dataset

validationlm$sales_predicted <- predict.lm( model4 , validationlm) validationlm <- validationlm %>% mutate(dif_prop = abs(Weekly_Sales - sales_predicted)/Weekly_Sales)

hist(validationlm$dif_prop)

How to calculate R^2

mean_sales_val <- mean(validationlm$Weekly_Sales) vallmR2 <- validationlm %>% mutate(res2 = (Weekly_Sales - sales_predicted)^2 , tot2 = (Weekly_Sales - mean_sales_val)^2)

r2 <- 1- sum(vallmR2\(res2)/sum(vallmR2\)tot2)

The model, using the training data, has a R^2 of 0.9282

The model, using the validation data, has a R^2 of 0.9302

Interpret 3 predictors

Fuel Price: When fuel prices go up, sales go down

Holiday_Flag: Sales increase during holidays

CPI: As the CPI goes up, so do sales

```