#2 Ceragamos base de datos
df <- read.csv("Data/Sample - Superstore.csv")
head(df)
## Row.ID Order.ID Order.Date Ship.Date Ship.Mode Customer.ID
## 1 1 CA-2016-152156 11/08/2016 11/11/2016 Second Class CG-12520
## 2 2 CA-2016-152156 11/08/2016 11/11/2016 Second Class CG-12520
## 3 3 CA-2016-138688 06/12/2016 6/16/2016 Second Class DV-13045
## 4 4 US-2015-108966 10/11/2015 10/18/2015 Standard Class SO-20335
## 5 5 US-2015-108966 10/11/2015 10/18/2015 Standard Class SO-20335
## 6 6 CA-2014-115812 06/09/2014 6/14/2014 Standard Class BH-11710
## Customer.Name Segment Country City State
## 1 Claire Gute Consumer United States Henderson Kentucky
## 2 Claire Gute Consumer United States Henderson Kentucky
## 3 Darrin Van Huff Corporate United States Los Angeles California
## 4 Sean O'Donnell Consumer United States Fort Lauderdale Florida
## 5 Sean O'Donnell Consumer United States Fort Lauderdale Florida
## 6 Brosina Hoffman Consumer United States Los Angeles California
## Postal.Code Region Product.ID Category Sub.Category
## 1 42420 South FUR-BO-10001798 Furniture Bookcases
## 2 42420 South FUR-CH-10000454 Furniture Chairs
## 3 90036 West OFF-LA-10000240 Office Supplies Labels
## 4 33311 South FUR-TA-10000577 Furniture Tables
## 5 33311 South OFF-ST-10000760 Office Supplies Storage
## 6 90032 West FUR-FU-10001487 Furniture Furnishings
## Product.Name Sales
## 1 Bush Somerset Collection Bookcase 261.9600
## 2 Hon Deluxe Fabric Upholstered Stacking Chairs, Rounded Back 731.9400
## 3 Self-Adhesive Address Labels for Typewriters by Universal 14.6200
## 4 Bretford CR4500 Series Slim Rectangular Table 957.5775
## 5 Eldon Fold 'N Roll Cart System 22.3680
## 6 Eldon Expressions Wood and Plastic Desk Accessories, Cherry Wood 48.8600
## Quantity Discount Profit
## 1 2 0.00 41.9136
## 2 3 0.00 219.5820
## 3 2 0.00 6.8714
## 4 5 0.45 -383.0310
## 5 2 0.20 2.5164
## 6 7 0.00 14.1694
#3 Modificacion de columnas
df_mod <- df %>% #llamar la base de datos
filter(State == "Ohio") %>%
select(Order.Date, Sales) %>% #Seleccionamos dos columnas Order.Date y Sales
mutate(Order.Date = mdy(Order.Date)) %>% #Cambiar a fecha
mutate(Fecha = floor_date(Order.Date, unit = "month")) %>% #Regresar a inicio de mes
group_by(Fecha)%>% #Agrupar por mes
summarise(Ventas = sum(Sales)) %>% #Hacer la suma
mutate(Mes = seq_along(Fecha)) # Crear la columana x para la regresion
head(df_mod)
## # A tibble: 6 × 3
## Fecha Ventas Mes
## <date> <dbl> <int>
## 1 2014-01-01 40.8 1
## 2 2014-02-01 19.5 2
## 3 2014-03-01 725. 3
## 4 2014-04-01 976. 4
## 5 2014-05-01 971. 5
## 6 2014-06-01 49.0 6
#4 Visualización
df_mod %>%
ggplot(., aes(x=Mes, y=Ventas)) +
geom_point() +
geom_line() +
geom_smooth(method = "lm", formula = "y ~ x")
#5 Grafica de caja y bogotes
#Esta grafica me sirve para encontrar valores atipicos
df_mod %>%
ggplot(., aes(x=Ventas))+
geom_boxplot()
#6 Revisar si la variable y tiene una distribucion aprox normal
df_mod %>%
ggplot(., aes(x=Ventas)) +
geom_histogram(bins = 30, aes(y=..density..)) +
geom_density()
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
#7 Analisi de correlacion
# Calculamos coeficientes de correlacion de Pearson, con Mes como x
with(df_mod, cor.test(Mes, Ventas))
##
## Pearson's product-moment correlation
##
## data: Mes and Ventas
## t = 1.8531, df = 44, p-value = 0.07059
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## -0.02304054 0.51883096
## sample estimates:
## cor
## 0.2690571
#La correlacion va de -1 a 1
#Valores extremos indican correlaciones mas fuertes
#Puede ser positiva (suben o bajan juntas) o
#negativa ( si una sube la otra baja y viceversa)
#8 Modelo de regresion
modelo_lineal <- lm(Ventas ~ Mes, data = df_mod)
stargazer(modelo_lineal, type = "text")
##
## ===============================================
## Dependent variable:
## ---------------------------
## Ventas
## -----------------------------------------------
## Mes 40.384*
## (21.793)
##
## Constant 752.238
## (588.215)
##
## -----------------------------------------------
## Observations 46
## R2 0.072
## Adjusted R2 0.051
## Residual Std. Error 1,962.298 (df = 44)
## F Statistic 3.434* (df = 1; 44)
## ===============================================
## Note: *p<0.1; **p<0.05; ***p<0.01
# el modelo es y= a + bx
#pendiente=b
#mes = x
#9 Coeficientes del modelo
#Obtener los coeficientes del modelo es decir a y b
coeficientes <- coef(modelo_lineal)
intercepto <- coeficientes["(Intercept)"]
pendiente <- coeficientes["Mes"]
#Crear el texto de la ecuacion
ecuacion <- paste0("y = ", round(intercepto,2),
"+",
round(pendiente, 2), "x")
ecuacion
## [1] "y = 752.24+40.38x"
#10 Prediccion
#Extender la serie temporal para 6 mese
df_futuro <- data.frame(Fecha = seq.Date(from = max(df_mod$Fecha)+ months(1),
by = "month",
length.out = 6),
Mes = seq(from = 49, to = 54, by = 1))
df_futuro
## Fecha Mes
## 1 2018-01-01 49
## 2 2018-02-01 50
## 3 2018-03-01 51
## 4 2018-04-01 52
## 5 2018-05-01 53
## 6 2018-06-01 54
#Generar las predicciones para 6 meses con intervalos de confianza
predicciones <- predict(modelo_lineal,
newdata = df_futuro,
interval = "confidence")
predicciones
## fit lwr upr
## 1 2731.058 1468.366 3993.749
## 2 2771.442 1469.634 4073.249
## 3 2811.826 1470.605 4153.046
## 4 2852.210 1471.304 4233.116
## 5 2892.594 1471.753 4313.435
## 6 2932.978 1471.974 4393.982
#11 Juntar datos
#Covertir prediciones a un data frame
df_predicciones <- as.data.frame(predicciones)
colnames(df_predicciones) <- c("Ventas", "Bajo", "Alto")
#Unir las predicciones y los intervalos de confianza con las fechas
df_futuro <- cbind(df_futuro, df_predicciones) #cbind une por columnas
#Unir con la base de datos original
df_total <- bind_rows(df_mod, df_futuro)
tail(df_total)
## # A tibble: 6 × 5
## Fecha Ventas Mes Bajo Alto
## <date> <dbl> <dbl> <dbl> <dbl>
## 1 2018-01-01 2731. 49 1468. 3994.
## 2 2018-02-01 2771. 50 1470. 4073.
## 3 2018-03-01 2812. 51 1471. 4153.
## 4 2018-04-01 2852. 52 1471. 4233.
## 5 2018-05-01 2893. 53 1472. 4313.
## 6 2018-06-01 2933. 54 1472. 4394.
#12 Visualizacion
#Grafica con valores pasado y prediccion
df_total %>%
ggplot(., aes(x = Fecha, y = Ventas)) +
geom_point(data = df_mod) +
geom_line(data = df_mod)+
geom_smooth(method = "lm", formula = y ~ x , color = "blue", data = df_mod)+
geom_ribbon(data = df_futuro, aes(ymin = Bajo, ymax = Alto),
fill = "lightblue")+
geom_point(data = df_futuro, aes(y = Ventas), color = "red")+
geom_line(data = df_futuro, aes(y = Ventas, color = "red",
linetype = "dashed"))