1 Cargar los paquetes necesarios

2 Cargar base de datos

df <- read.csv("Sample - Superstore.csv")
head(df)
##   Row.ID       Order.ID Order.Date  Ship.Date      Ship.Mode Customer.ID
## 1      1 CA-2016-152156  11/8/2016 11/11/2016   Second Class    CG-12520
## 2      2 CA-2016-152156  11/8/2016 11/11/2016   Second Class    CG-12520
## 3      3 CA-2016-138688  6/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   6/9/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

# Nota: la prediccion que vamos a hacer considera valores corrientes
df_mod <- df %>%  #Llama la base de datos
  filter(State == "California") %>% # ESTE ES EL PASO NUEVO
  select(Order.Date, Sales) %>%  # Selecciona dos columnas Order.Date y Sales
  mutate(Order.Date = mdy(Order.Date)) %>% # Cambia formato a fecha
   mutate(Fecha = floor_date(Order.Date, unit = "month")) %>%  # Asigna las fechas a primero de mes
  group_by(Fecha) %>%
  summarise(Ventas = sum(Sales)) %>%
  mutate(Mes = seq_along(Fecha))  # Crear variable x para facilitar la regresion
head(df_mod)
## # A tibble: 6 × 3
##   Fecha      Ventas   Mes
##   <date>      <dbl> <int>
## 1 2014-01-01  2455.     1
## 2 2014-02-01   309.     2
## 3 2014-03-01  7239.     3
## 4 2014-04-01  8165.     4
## 5 2014-05-01  5960.     5
## 6 2014-06-01  4379.     6

4 Visualizacion del objetivo

df_mod %>%
  ggplot(., aes(x=Mes, y=Ventas)) +
  geom_point() +
  geom_line() +
  geom_smooth(method = "lm", formula = "y ~ x")

Graficas de caja y bigotes

# Esta grafica me sirve para detectar valores aripicos
df_mod %>%
  ggplot(., aes(x=Ventas)) +
  geom_boxplot()

Analisis de normalidad

# Revisar que la variable y tenga una distribucion mas o menos 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 Analisis de correlacion

# Calculamos el coeficiente de correlacion de Pearson
with(df_mod, cor.test(Mes, Ventas))
## 
##  Pearson's product-moment correlation
## 
## data:  Mes and Ventas
## t = 4.0151, df = 46, p-value = 0.0002173
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.2634175 0.6932186
## sample estimates:
##       cor 
## 0.5094238
# La correlacion va de -1 a 1
# Valores extremos indican correlacion mas fuerte
# Puede ser positiva (suben o bajan juntas) o
# negativa (si una suba 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                         197.337***         
##                              (49.148)          
##                                                
## Constant                   4,700.394***        
##                             (1,383.306)        
##                                                
## -----------------------------------------------
## Observations                    48             
## R2                             0.260           
## Adjusted R2                    0.243           
## Residual Std. Error     4,717.228 (df = 46)    
## F Statistic           16.121*** (df = 1; 46)   
## ===============================================
## Note:               *p<0.1; **p<0.05; ***p<0.01
# El modelo que buscamos estimar es: y = a + bx
# En este caso
# Constant = a
# 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 = 4700.39 + 197.34x"

10 Generacion de preddiciones

# Vamos a extender la serie temporal 6 meses
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))

# Generar las predicciones para 6 meses con intervalos de confianza
predicciones <- predict(modelo_lineal,
                        newdata = df_futuro,
                        interval = "confidence")
predicciones
##        fit      lwr      upr
## 1 14369.92 11585.47 17154.37
## 2 14567.26 11696.28 17438.24
## 3 14764.60 11806.31 17722.89
## 4 14961.94 11915.63 18008.24
## 5 15159.27 12024.30 18294.25
## 6 15356.61 12132.37 18580.85

11 Juntar datos

# Convertir a data frame
df_predicciones <- as.data.frame(predicciones)
colnames(df_predicciones) <- c("Ventas", "Bajo", "Alto")

# Unir las predicciones con las fechas
df_futuro<- cbind(df_futuro, df_predicciones) # cbind unir por columnas

# Unir con la base de datos original
df_total <- bind_rows(df_mod, df_futuro)
tail(df_total, 7)
## # A tibble: 7 × 5
##   Fecha      Ventas   Mes   Bajo   Alto
##   <date>      <dbl> <dbl>  <dbl>  <dbl>
## 1 2017-12-01 19318.    48    NA     NA 
## 2 2018-01-01 14370.    49 11585. 17154.
## 3 2018-02-01 14567.    50 11696. 17438.
## 4 2018-03-01 14765.    51 11806. 17723.
## 5 2018-04-01 14962.    52 11916. 18008.
## 6 2018-05-01 15159.    53 12024. 18294.
## 7 2018-06-01 15357.    54 12132. 18581.

12 Visualizacion

df_total %>%
  ggplot(., aes(x = Fecha, y = Ventas)) +
  geom_point(dara = df_mod) + # Valores historicos
  geom_line(data = df_mod) + # Linea de valores historicos
  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") + # Valores predichos
  geom_line(data = df_futuro, aes(y = Ventas), color = "red", linetype = "dashed") +
  labs(title = "Prediccion de ventas enero-junio 2018",
       x = "Mes",
       y = "Ventas")
## Warning in geom_point(dara = df_mod): Ignoring unknown parameters: `dara`