1 Actividades

  1. Análisis estadístico
  2. Análisis exploratorio (EDA)
  3. Análisis visual
  4. Regresión lineal y múltiple.
  5. Utilizaremos tres conjuntos de datos diferentes: mtcars, iris

2 Cargamos las librerias 📔

library(tidyverse)
library(ggplot2)
library(readr)
library(dplyr)
library(broom)

3 Cargar datos

3.1 Dataset 1: mtcars 🚘

data(mtcars)
head(mtcars)

4 Dataset 2: iris 💐

data(iris)
head(iris)

5 Dataset 3: ventas_2023.csv ⚖

Asegúrate de tener el archivo “ventas_2023.csv” en tu directorio de trabajo

5.1 Creando datos como CSV

set.seed(123)  # Para reproducibilidad
ventas_data <- data.frame(
  fecha = seq(as.Date("2023-01-01"), as.Date("2023-12-31"), by="day"),
  ventas = runif(365, 100, 1000),
  categoria = sample(c("A", "B", "C"), 365, replace = TRUE),
  region = sample(c("Norte", "Sur", "Este", "Oeste"), 365, replace = TRUE)
)
# Guardando el conjunto de datos como CSV
write.csv(ventas_data, "ventas_2023.csv", row.names = FALSE)

# Cargando el archivo CSV
ventas <- read.csv("ventas_2023.csv")

# Examinando las primeras filas
head(ventas)

6 Análisis estadístico básico

summary_stats_mtcars <- summary(mtcars)
summary_stats_iris <- summary(iris)
summary_stats_example <- summary(ventas)
print("Resumen estadístico de mtcars:")
print(summary_stats_mtcars)

print("Resumen estadístico de iris:")
print(summary_stats_iris)

print("Resumen estadístico de example_data:")
print(summary_stats_example)

7 Análisis exploratorio de datos (EDA)

7.1 Usamos ggplot2 para visualizar mtcars

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() + 
  labs(title = "Relación entre peso y millas por galón (mtcars)", x = "Peso", y = "Millas por galón") +
  theme_minimal()

7.2 Usamos ggplot2 para visualizar Iris

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + 
  geom_point() + 
  labs(title = "Relación entre longitud y ancho del sépalo (iris)", x = "Longitud del sépalo", y = "Ancho del sépalo") +
  theme_minimal()

8 Análisis visual

8.1 Histograma para ejemplo ventas

ggplot(ventas, aes(x = ventas)) + 
  geom_histogram(binwidth = 5, fill = "blue", color = "black") + 
  labs(title = "Distribución de una variable en example_data", x = "Variable", y = "Frecuencia") +
  theme_minimal()

9 Regresión lineal simple

9.1 Usando mtcars

modelo_lineal <- lm(mpg ~ wt, data = mtcars)
summary(modelo_lineal)
## 
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.5432 -2.3647 -0.1252  1.4096  6.8727 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  37.2851     1.8776  19.858  < 2e-16 ***
## wt           -5.3445     0.5591  -9.559 1.29e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.046 on 30 degrees of freedom
## Multiple R-squared:  0.7528, Adjusted R-squared:  0.7446 
## F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10

10 Visualización de la regresión lineal

ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE, color = "red") + 
  labs(title = "Regresión lineal simple: mpg vs wt", x = "Peso", y = "Millas por galón") +
  theme_minimal()

11 Regresión múltiple

11.1 Usando iris

modelo_multiple <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, data = iris)
summary(modelo_multiple)
## 
## Call:
## lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width, 
##     data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.82816 -0.21989  0.01875  0.19709  0.84570 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   1.85600    0.25078   7.401 9.85e-12 ***
## Sepal.Width   0.65084    0.06665   9.765  < 2e-16 ***
## Petal.Length  0.70913    0.05672  12.502  < 2e-16 ***
## Petal.Width  -0.55648    0.12755  -4.363 2.41e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3145 on 146 degrees of freedom
## Multiple R-squared:  0.8586, Adjusted R-squared:  0.8557 
## F-statistic: 295.5 on 3 and 146 DF,  p-value: < 2.2e-16

11.2 Implementación en R:

library(qcc)

# Datos de proceso
mediciones <- matrix(
  rnorm(100, mean = 10, sd = 0.1) + 
    rep(c(0, 0, 0, 0, 0.5), each = 20), 
  ncol = 5
)

# Gráfico de control X-bar
qcc_result <- qcc(mediciones, type = "xbar")

summary(qcc_result)
## 
## Call:
## qcc(data = mediciones, type = "xbar")
## 
## xbar chart for mediciones 
## 
## Summary of group statistics:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
##  9.98147 10.06417 10.08746 10.08738 10.10558 10.18838 
## 
## Group sample size:  5
## Number of groups:  20
## Center of group statistics:  10.08738
## Standard deviation:  0.2611976 
## 
## Control limits:
##       LCL      UCL
##  9.736948 10.43781
# Capacidad de proceso
process.capability(qcc_result, spec.limits = c(9.5, 10.5))

## 
## Process Capability Analysis
## 
## Call:
## process.capability(object = qcc_result, spec.limits = c(9.5,     10.5))
## 
## Number of obs = 100          Target = 10
##        Center = 10.09           LSL = 9.5
##        StdDev = 0.2612          USL = 10.5
## 
## Capability indices:
## 
##        Value    2.5%   97.5%
## Cp    0.6381  0.5493  0.7267
## Cp_l  0.7496  0.6462  0.8530
## Cp_u  0.5266  0.4441  0.6090
## Cp_k  0.5266  0.4283  0.6248
## Cpm   0.6051  0.5172  0.6929
## 
## Exp<LSL 1.2%  Obs<LSL 0%
## Exp>USL 5.7%  Obs>USL 9%

12 Guardar resultados

saveRDS(modelo_lineal, "modelo_lineal.rds")
saveRDS(modelo_multiple, "modelo_multiple.rds")