#limpiamos la consola
rm(list = ls())
getwd() #Ubicamos el directorio
## [1] "C:/Users/tin_m/OneDrive/Documentos/IBERO/Métodos cuantis/Trabajo final"
setwd("C:/Users/tin_m/OneDrive/Documentos/IBERO/Métodos cuantis/Trabajo final") #Con setwd cambiamos el directorio raiz
getwd()
## [1] "C:/Users/tin_m/OneDrive/Documentos/IBERO/Métodos cuantis/Trabajo final"
list.files() #Permite ver que archivos tengo en la carpeta
## [1] "archive.zip" "BASES DE DATOS PERSONALIDAD.csv"
## [3] "E-commerce.csv" "Online Sales Data.csv"
## [5] "rsconnect" "trabajo-final_métodos-cuantis.html"
## [7] "trabajo-final_métodos-cuantis.Rmd" "trabajo final_métodos cuantis.Rmd"
## [9] "walmart sales.zip" "Walmart_Sales.csv"
base <- read.csv("Walmart_Sales.csv") #creamos nuestra base
names(base)#exploramos las variables (campos) de la base de datos
## [1] "Store" "Date" "Weekly_Sales" "Holiday_Flag" "Temperature"
## [6] "Fuel_Price" "CPI" "Unemployment"
library(tidyverse) #primer libreria
## ── 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.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── 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
#install.packages("skimr")
library(skimr)
## Warning: package 'skimr' was built under R version 4.3.3
skimr::skim(base) #Estadísticas descriptivas y distribución de las variables en el modelo
| Name | base |
| Number of rows | 6435 |
| Number of columns | 8 |
| _______________________ | |
| Column type frequency: | |
| character | 1 |
| numeric | 7 |
| ________________________ | |
| Group variables | None |
Variable type: character
| skim_variable | n_missing | complete_rate | min | max | empty | n_unique | whitespace |
|---|---|---|---|---|---|---|---|
| Date | 0 | 1 | 10 | 10 | 0 | 143 | 0 |
Variable type: numeric
| skim_variable | n_missing | complete_rate | mean | sd | p0 | p25 | p50 | p75 | p100 | hist |
|---|---|---|---|---|---|---|---|---|---|---|
| Store | 0 | 1 | 23.00 | 12.99 | 1.00 | 12.00 | 23.00 | 34.00 | 45.00 | ▇▇▇▇▇ |
| Weekly_Sales | 0 | 1 | 1046964.88 | 564366.62 | 209986.25 | 553350.10 | 960746.04 | 1420158.66 | 3818686.45 | ▇▆▂▁▁ |
| Holiday_Flag | 0 | 1 | 0.07 | 0.26 | 0.00 | 0.00 | 0.00 | 0.00 | 1.00 | ▇▁▁▁▁ |
| Temperature | 0 | 1 | 60.66 | 18.44 | -2.06 | 47.46 | 62.67 | 74.94 | 100.14 | ▁▃▆▇▃ |
| Fuel_Price | 0 | 1 | 3.36 | 0.46 | 2.47 | 2.93 | 3.44 | 3.73 | 4.47 | ▆▆▇▇▁ |
| CPI | 0 | 1 | 171.58 | 39.36 | 126.06 | 131.74 | 182.62 | 212.74 | 227.23 | ▇▁▁▂▆ |
| Unemployment | 0 | 1 | 8.00 | 1.88 | 3.88 | 6.89 | 7.87 | 8.62 | 14.31 | ▂▇▆▁▁ |
str(base) # Verifica la estructura y los tipos de datos
## 'data.frame': 6435 obs. of 8 variables:
## $ Store : int 1 1 1 1 1 1 1 1 1 1 ...
## $ Date : chr "05-02-2010" "12-02-2010" "19-02-2010" "26-02-2010" ...
## $ Weekly_Sales: num 1643691 1641957 1611968 1409728 1554807 ...
## $ Holiday_Flag: int 0 1 0 0 0 0 0 0 0 0 ...
## $ Temperature : num 42.3 38.5 39.9 46.6 46.5 ...
## $ Fuel_Price : num 2.57 2.55 2.51 2.56 2.62 ...
## $ CPI : num 211 211 211 211 211 ...
## $ Unemployment: num 8.11 8.11 8.11 8.11 8.11 ...
library(ggcorrplot)
## Warning: package 'ggcorrplot' was built under R version 4.3.3
corr_selected <- base %>%
select(Store, Weekly_Sales, Temperature, Fuel_Price, CPI, Unemployment) %>%
# calcular la matriz de correlación y redondear a un decimal
cor(use = "pairwise") %>%
round(1)
ggcorrplot(corr_selected, type = "lower", lab = T, show.legend = F)
str(base$Weekly_Sales)
## num [1:6435] 1643691 1641957 1611968 1409728 1554807 ...
ggplot(base, aes(x = Weekly_Sales, na.rm = T)) +
geom_histogram() +
labs(x = "Ventas semanales", y = " Frecuencia",
title = " Distribución de la variable dependiente") #Exploración visual de la variable dependiente
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#Ventas semanales
ggplot(base, aes(x = Weekly_Sales)) +
geom_histogram(bins = 20, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Ventas semanales",
x = "Número de ventas",
y = "Frecuencia") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
#IPC
ggplot(base, aes(x = CPI)) +
geom_histogram(binwidth = 5, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Variable Índice de Precios al Consumidor",
x = "CPI",
y = "Frecuencia") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
#Temperatura
ggplot(base, aes(x = Temperature)) +
geom_histogram(binwidth = 5, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Variable temperatura",
x = "Temperatura en grados Farenheit (°F)",
y = "Frecuencia") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
#Precio de combustible
ggplot(base, aes(x = Fuel_Price)) +
geom_histogram(binwidth = 5, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Variable Precio de la Gasolina",
x = "Precio de la Gasolina",
y = "Frecuencia") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
#Desempleo
ggplot(base, aes(x = Unemployment)) +
geom_histogram(bins = 10, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Tasa de Desempleo Semanal",
x = "Desempleo",
y = "Tasa de porcentaje del Desemplo") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
#Dias Festivos
ggplot(base, aes(x = Holiday_Flag)) +
geom_histogram(bins = 2, fill = "#D2B48C", color = "black", size = 0.3) +
labs(title = "Días Festivos",
x = "Numero De Días Festivos",
y = "Frecuencia") +
theme_minimal() +
theme(
plot.title = element_text(hjust = 0.5, size = 18, face = "bold"),
axis.title = element_text(size = 12),
axis.text = element_text(size=10))
ggplot(base, aes(Weekly_Sales, Temperature)) +
geom_point() +
labs(x = " Ventas semanales", y = "Temperatura")
## Modelo lineal simple
modelo1 <- lm(Weekly_Sales ~ Temperature, data = base)
summary(modelo1)
##
## Call:
## lm(formula = Weekly_Sales ~ Temperature, data = base)
##
## Residuals:
## Min 1Q Median 3Q Max
## -871164 -488496 -91696 386226 2713005
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1165406.0 24139.0 48.279 < 2e-16 ***
## Temperature -1952.4 380.7 -5.128 3.01e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 563300 on 6433 degrees of freedom
## Multiple R-squared: 0.004072, Adjusted R-squared: 0.003917
## F-statistic: 26.3 on 1 and 6433 DF, p-value: 3.008e-07
#install.packages("texreg")
library(texreg)
## Warning: package 'texreg' was built under R version 4.3.3
## Version: 1.39.4
## Date: 2024-07-23
## Author: Philip Leifeld (University of Manchester)
##
## Consider submitting praise using the praise or praise_interactive functions.
## Please cite the JSS article in your publications -- see citation("texreg").
##
## Attaching package: 'texreg'
## The following object is masked from 'package:tidyr':
##
## extract
screenreg(modelo1,
custom.model.names = "Modelo 1",
custom.coef.names = c("Constante", "Temperatura"))
##
## ===========================
## Modelo 1
## ---------------------------
## Constante 1165406.01 ***
## (24138.95)
## Temperatura -1952.42 ***
## (380.71)
## ---------------------------
## R^2 0.00
## Adj. R^2 0.00
## Num. obs. 6435
## ===========================
## *** p < 0.001; ** p < 0.01; * p < 0.05
#Representación gráfica
ggplot(data = base, # seleccionamos la base de datos
aes(x = Temperature, y = Weekly_Sales))+ # variables independientes y dependientes
geom_point() + # los valores observados son graficados
geom_smooth(method = "lm", # La línea de regresión se superpone
se = F, # el área de error no se grafica con un IC del 95%
color = "blue")+ # color de la línea
labs (x = "Temperatura", y = "Ventas semanales")
## `geom_smooth()` using formula = 'y ~ x'
#Representación gráfica del error de predicción de la línea.
ggplot(data = base, aes(x = Temperature, y = Weekly_Sales))+
geom_point() +
geom_smooth(method = "lm", color = "blue",
se = T) + # añadimos la predicción
labs(x = "Temperatura", y = "Ventas semanales",
title = " Ajuste lineal entre la Temperatura y las Ventas semanales en Walmart")
## `geom_smooth()` using formula = 'y ~ x'
#Eliminamos NAs
base <- base %>%
drop_na(Weekly_Sales, Temperature, Fuel_Price, CPI, Unemployment, Holiday_Flag)
#Corremos el modelo
modelo2 <- lm(Weekly_Sales ~ Temperature + Fuel_Price + CPI + Unemployment +
factor(Holiday_Flag),
data = base)
summary(modelo2)
##
## Call:
## lm(formula = Weekly_Sales ~ Temperature + Fuel_Price + CPI +
## Unemployment + factor(Holiday_Flag), data = base)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1022429 -478555 -117266 397246 2800620
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1726523.4 79763.5 21.646 < 2e-16 ***
## Temperature -724.2 400.5 -1.808 0.07060 .
## Fuel_Price -10167.9 15762.8 -0.645 0.51891
## CPI -1598.9 195.1 -8.194 3.02e-16 ***
## Unemployment -41552.3 3972.7 -10.460 < 2e-16 ***
## factor(Holiday_Flag)1 74891.7 27639.3 2.710 0.00675 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 557400 on 6429 degrees of freedom
## Multiple R-squared: 0.02544, Adjusted R-squared: 0.02469
## F-statistic: 33.57 on 5 and 6429 DF, p-value: < 2.2e-16
screenreg(modelo2)
##
## =====================================
## Model 1
## -------------------------------------
## (Intercept) 1726523.39 ***
## (79763.46)
## Temperature -724.17
## (400.46)
## Fuel_Price -10167.88
## (15762.78)
## CPI -1598.87 ***
## (195.13)
## Unemployment -41552.28 ***
## (3972.66)
## factor(Holiday_Flag)1 74891.66 **
## (27639.35)
## -------------------------------------
## R^2 0.03
## Adj. R^2 0.02
## Num. obs. 6435
## =====================================
## *** p < 0.001; ** p < 0.01; * p < 0.05
#Selección del modelo usando stepwise
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
modelo_step <- stepAIC(modelo2, direction = "both")
## Start: AIC=170288.5
## Weekly_Sales ~ Temperature + Fuel_Price + CPI + Unemployment +
## factor(Holiday_Flag)
##
## Df Sum of Sq RSS AIC
## - Fuel_Price 1 1.2926e+11 1.9973e+15 170287
## <none> 1.9971e+15 170288
## - Temperature 1 1.0159e+12 1.9982e+15 170290
## - factor(Holiday_Flag) 1 2.2808e+12 1.9994e+15 170294
## - CPI 1 2.0857e+13 2.0180e+15 170353
## - Unemployment 1 3.3986e+13 2.0311e+15 170395
##
## Step: AIC=170286.9
## Weekly_Sales ~ Temperature + CPI + Unemployment + factor(Holiday_Flag)
##
## Df Sum of Sq RSS AIC
## <none> 1.9973e+15 170287
## + Fuel_Price 1 1.2926e+11 1.9971e+15 170288
## - Temperature 1 1.2011e+12 1.9985e+15 170289
## - factor(Holiday_Flag) 1 2.3395e+12 1.9996e+15 170292
## - CPI 1 2.1228e+13 2.0185e+15 170353
## - Unemployment 1 3.3988e+13 2.0313e+15 170393
summary(modelo_step)
##
## Call:
## lm(formula = Weekly_Sales ~ Temperature + CPI + Unemployment +
## factor(Holiday_Flag), data = base)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1020421 -477999 -115859 396128 2800875
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1687798.2 52515.7 32.139 < 2e-16 ***
## Temperature -773.1 393.2 -1.966 0.04930 *
## CPI -1570.0 189.9 -8.267 < 2e-16 ***
## Unemployment -41235.7 3942.0 -10.460 < 2e-16 ***
## factor(Holiday_Flag)1 75760.1 27605.3 2.744 0.00608 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 557300 on 6430 degrees of freedom
## Multiple R-squared: 0.02538, Adjusted R-squared: 0.02477
## F-statistic: 41.86 on 4 and 6430 DF, p-value: < 2.2e-16
modelo_Final <- lm(formula = Weekly_Sales ~ Temperature + CPI + Unemployment +
factor(Holiday_Flag), data = base)
summary(modelo_Final)
##
## Call:
## lm(formula = Weekly_Sales ~ Temperature + CPI + Unemployment +
## factor(Holiday_Flag), data = base)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1020421 -477999 -115859 396128 2800875
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1687798.2 52515.7 32.139 < 2e-16 ***
## Temperature -773.1 393.2 -1.966 0.04930 *
## CPI -1570.0 189.9 -8.267 < 2e-16 ***
## Unemployment -41235.7 3942.0 -10.460 < 2e-16 ***
## factor(Holiday_Flag)1 75760.1 27605.3 2.744 0.00608 **
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 557300 on 6430 degrees of freedom
## Multiple R-squared: 0.02538, Adjusted R-squared: 0.02477
## F-statistic: 41.86 on 4 and 6430 DF, p-value: < 2.2e-16
screenreg(modelo_Final)
##
## =====================================
## Model 1
## -------------------------------------
## (Intercept) 1687798.23 ***
## (52515.74)
## Temperature -773.15 *
## (393.18)
## CPI -1570.01 ***
## (189.92)
## Unemployment -41235.66 ***
## (3942.04)
## factor(Holiday_Flag)1 75760.15 **
## (27605.28)
## -------------------------------------
## R^2 0.03
## Adj. R^2 0.02
## Num. obs. 6435
## =====================================
## *** p < 0.001; ** p < 0.01; * p < 0.05
library(stargazer)
##
## Please cite as:
## Hlavac, Marek (2022). stargazer: Well-Formatted Regression and Summary Statistics Tables.
## R package version 5.2.3. https://CRAN.R-project.org/package=stargazer
stargazer(modelo_Final)
##
## % Table created by stargazer v.5.2.3 by Marek Hlavac, Social Policy Institute. E-mail: marek.hlavac at gmail.com
## % Date and time: jue., sep. 26, 2024 - 10:15:29 p. m.
## \begin{table}[!htbp] \centering
## \caption{}
## \label{}
## \begin{tabular}{@{\extracolsep{5pt}}lc}
## \\[-1.8ex]\hline
## \hline \\[-1.8ex]
## & \multicolumn{1}{c}{\textit{Dependent variable:}} \\
## \cline{2-2}
## \\[-1.8ex] & Weekly\_Sales \\
## \hline \\[-1.8ex]
## Temperature & $-$773.147$^{**}$ \\
## & (393.179) \\
## & \\
## CPI & $-$1,570.005$^{***}$ \\
## & (189.917) \\
## & \\
## Unemployment & $-$41,235.660$^{***}$ \\
## & (3,942.040) \\
## & \\
## factor(Holiday\_Flag)1 & 75,760.150$^{***}$ \\
## & (27,605.280) \\
## & \\
## Constant & 1,687,798.000$^{***}$ \\
## & (52,515.740) \\
## & \\
## \hline \\[-1.8ex]
## Observations & 6,435 \\
## R$^{2}$ & 0.025 \\
## Adjusted R$^{2}$ & 0.025 \\
## Residual Std. Error & 557,331.900 (df = 6430) \\
## F Statistic & 41.862$^{***}$ (df = 4; 6430) \\
## \hline
## \hline \\[-1.8ex]
## \textit{Note:} & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
## \end{tabular}
## \end{table}
#R2 (cuanto más alto, mejor),
#AIC (Akaike Information Criteria) (cuanto más bajo, mejor a la hora de decidir entre múltiples modelos).
confint(modelo_Final)[5, ]
## 2.5 % 97.5 %
## 21644.61 129875.69
#Descripción de variables
#Store: Store number
#Date: Sales week start date
#Weekly_Sales: Sales
#Holiday_Flag: Mark on the presence or absence of a holiday
#Temperature: Air temperature in the region
#Fuel_Price: Fuel cost in the region
#CPI: Consumer price index
#Unemployment: Unemployment rate
#Prueba de hipótesis para los coeficientes:
#Ho: Betai = 0. El coeficiente de la variable "i" es igual a cero. No tiene relación alguna nuestra variable indep con nuestra variable dep.
#vs
#Ha: Betai != 0. El coeficiente de la variable "i" es diferente a cero. si existe relación entre las variables.
#Regla de decisión:
#Rechazar Ho si p-valor es menor al 0.05%
#Beta 1 (Temperatura)
# Estimate Std. Error t value Pr(>|t|)
#Temperature -773.1 393.2 -1.966 0.04930 *
#Se rechaza la hipótesis nula a favor de la alternativa, es decir que la temperatura si tiene un efecto en las ventas semanales. La variable de temperatura es significativa al 99% de confianza.
#El efecto de la temperatura en los niveles de ventas semanales es negativo, eso significa que a medida que aumente la temperatura, disminuirán las ventas.
#Cuando la temperatura aumenta en un grado en la región, las ventas semanales disminuirán en 773.1 dólares, manteniendo todo lo demás constante.
#Beta 2 (IPC)
# Estimate Std. Error t value Pr(>|t|)
#CPI -1570.0 189.9 -8.267 < 2e-16 ***
#Se rechaza la hipótesis nula a favor de la alternativa, es decir que el CIP tiene un efecto en las ventas semanales. La variable de CPI es significativa al 99% de confianza.
#El efecto del CPI en los niveles de ventas semanales es negativo, eso significa que a medida que aumente el CPI, disminuirán las ventas.
#Cuando el IPC aumenta en un punto, las ventas semanales disminuirán en 1570 dólares, manteniendo todo lo demás constante.
#Beta 3 (Tasa de desempleo)
# Estimate Std. Error t value Pr(>|t|)
#Unemployment -41235.7 3942.0 -10.460 < 2e-16 ***
#Se rechaza la hipótesis nula a favor de la alternativa, es decir que la variable de desemplo si tiene un efecto en las ventas semanales. La variable de temperatura es significativa al 99% de confianza.
#El efecto de la temperatura en los niveles de ventas semanales es negativo, eso significa que a medida que aumente la tasa de desemplo, disminuirán las ventas.
#Cuando la tasa de desemplo aumenta en un grado en la región, las ventas semanales disminuirán en 41235.7 millones de dólares, manteniendo todo lo demás constante.
#Beta 4 Variable nominal o dicotómica. (Dias de descanso)
# Estimate Std. Error t value Pr(>|t|)
#factor(Holiday_Flag)1 75760.1 27605.3 2.744 0.00608 **
#El coeficiente de dias de descanso es 75760.1, significativo en el 99%. ¿Cómo interpretamos este coeficiente? Simplemente, el valor predicho de las ventas es 75760.1 unidades(dólares) superior cuando existe un dia de descanso, para cualquier valor de los otros x′s. En otras palabras, se ganan $75,760 dlls por concepto de ventas semanales más cuando hay dias de descanso, manteniendo contantes las demás variables.
#Todo el modelo
#Rechazo la hipótesis nula que establece que al menos uno de los coeficientes de las variables sea igual a cero. El modelo es significativo a un nivel de confianza del 95% para todas las variables de manera global ya que tiene un p-valor menor a 0.05, con una R2 de 0.02538, es decir, el 2.5% de la variación del volumen de ventas semanales es explicado por el modelo.