Este documento muestra cómo realizar un análisis estadístico completo en R.

Incluye:

Cada sección incluye la fórmula estadística utilizada.

Introducción

El análisis de datos en estadística tiene como uno de sus principales objetivos comprender la relación entre variables. Para ello existen diferentes métodos estadísticos que permiten identificar asociaciones, medir la intensidad de la relación y construir modelos predictivos.

En este informe se desarrollan tres enfoques fundamentales:

Estos métodos constituyen herramientas esenciales en investigación científica, ciencias sociales, ingeniería y análisis de datos.

1 CARGAR LIBRERÍAS

library(readxl)
library(ggplot2)
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(haven)
library(moments)
library(nortest)
library(openxlsx)

2 CARGAR BASE DE DATOS

Se carga el archivo desde el explorador.

Alumnos <- read_excel("D:/6. CICIED/Lección 7/Alumnos.xlsx")

str(Alumnos)
## tibble [124 × 9] (S3: tbl_df/tbl/data.frame)
##  $ Id                  : num [1:124] 1 2 3 4 5 6 7 8 9 10 ...
##  $ Sexo                : chr [1:124] "M" "F" "F" "F" ...
##  $ Edad                : num [1:124] 70 63 16 30 24 57 27 49 33 64 ...
##  $ Area                : chr [1:124] "Sociales" "Sociales" "Ingenierías" "Biomédicas" ...
##  $ Nivel.Socioeconomico: num [1:124] 3 3 2 2 2 2 2 1 2 3 ...
##  $ TiempoDedicación    : chr [1:124] "De 2 a 5 horas" "De 5 horas a más" "Menos de 2 horas" "De 5 horas a más" ...
##  $ Trabaja             : chr [1:124] "Si" "No" "No" "No" ...
##  $ Rendimiento         : chr [1:124] "Regular" "Regular" "Regular" "Regular" ...
##  $ OpinionGestion      : chr [1:124] "Desaprueba" "Desaprueba" "Desaprueba" "Desaprueba" ...

INTERPRETACIÓN

summary(Alumnos)
##        Id             Sexo                Edad           Area          
##  Min.   :  1.00   Length:124         Min.   :15.00   Length:124        
##  1st Qu.: 31.75   Class :character   1st Qu.:29.00   Class :character  
##  Median : 62.50   Mode  :character   Median :40.00   Mode  :character  
##  Mean   : 62.50                      Mean   :42.16                     
##  3rd Qu.: 93.25                      3rd Qu.:57.00                     
##  Max.   :124.00                      Max.   :70.00                     
##  Nivel.Socioeconomico TiempoDedicación     Trabaja          Rendimiento       
##  Min.   :1.000        Length:124         Length:124         Length:124        
##  1st Qu.:1.000        Class :character   Class :character   Class :character  
##  Median :2.000        Mode  :character   Mode  :character   Mode  :character  
##  Mean   :1.758                                                                
##  3rd Qu.:2.000                                                                
##  Max.   :3.000                                                                
##  OpinionGestion    
##  Length:124        
##  Class :character  
##  Mode  :character  
##                    
##                    
## 

Describir:

head(Alumnos)
## # A tibble: 6 × 9
##      Id Sexo   Edad Area        Nivel.Socioeconomico TiempoDedicación Trabaja
##   <dbl> <chr> <dbl> <chr>                      <dbl> <chr>            <chr>  
## 1     1 M        70 Sociales                       3 De 2 a 5 horas   Si     
## 2     2 F        63 Sociales                       3 De 5 horas a más No     
## 3     3 F        16 Ingenierías                    2 Menos de 2 horas No     
## 4     4 F        30 Biomédicas                     2 De 5 horas a más No     
## 5     5 F        24 Ingenierías                    2 De 2 a 5 horas   Si     
## 6     6 F        57 Sociales                       2 De 2 a 5 horas   No     
## # ℹ 2 more variables: Rendimiento <chr>, OpinionGestion <chr>

3 CAMBIO DE NOMBRE DE VARIABLES

Se usa rename().

names(Alumnos)[5] <- "NivelSocioeconomico"

names(Alumnos)
## [1] "Id"                  "Sexo"                "Edad"               
## [4] "Area"                "NivelSocioeconomico" "TiempoDedicación"   
## [7] "Trabaja"             "Rendimiento"         "OpinionGestion"

4 CONVERTIR VARIABLE CUANTITATIVA A CATEGÓRICA

Edad <- Alumnos$Edad

Edad_cat <- cut(
  Edad,
  breaks = c(0,25,40,100),
  labels = c("Joven","Adulto","Mayor")
)

table(Edad_cat)
## Edad_cat
##  Joven Adulto  Mayor 
##     20     43     61

INTERPRETACIÓN

Analizar distribución de la edad.


5 RECODIFICAR VARIABLE CUALITATIVA

datos <- Alumnos %>%
  mutate(Area_cat = case_when(
    Area %in% c("Educación","Psicología") ~ "Social",
    Area == "Sociales" ~ "Social",
    Area == "Ingenierías" ~ "Ingeniería",
    TRUE ~ Area
  ))
table(datos$Area_cat)
## 
##  Biomédicas  Ingeniería Matemáticas      Social 
##          47          35           3          39

6 TABLAS DE CONTINGENCIA

tabla <- table(Alumnos$OpinionGestion, Alumnos$Sexo)

tabla
##             
##               F  M
##   Aprueba    21 31
##   Desaprueba 44 28

7 PORCENTAJES POR FILAS

FÓRMULA

Porcentaje por fila:

P_{ij} = (n_{ij} / n_{i}) * 100

Donde:

por_filas <- round(prop.table(tabla,1)*100,2)

por_filas
##             
##                  F     M
##   Aprueba    40.38 59.62
##   Desaprueba 61.11 38.89

8 PORCENTAJES POR COLUMNAS

FÓRMULA

P_{ij} = (n_{ij} / n_{j}) * 100

Donde:

por_columnas <- round(prop.table(tabla,2)*100,2)

por_columnas
##             
##                  F     M
##   Aprueba    32.31 52.54
##   Desaprueba 67.69 47.46

9 PORCENTAJES DEL TOTAL

FÓRMULA

P_{ij} = (n_{ij} / N) * 100

Donde:

por_total <- round(prop.table(tabla)*100,2)

por_total
##             
##                  F     M
##   Aprueba    16.94 25.00
##   Desaprueba 35.48 22.58

10 GRÁFICO DE CONTINGENCIA

df_tabla <- as.data.frame(tabla)
names(df_tabla)[1] = "OpinionGestion"
names(df_tabla)[2] = "Sexo"

grafico1 <- ggplot(df_tabla,
                   aes(x=Sexo,y=Freq,fill=OpinionGestion)) +
  geom_bar(stat="identity",position="dodge") +
  scale_fill_brewer(palette="Set2") +
  labs(title="Opinión de gestión según sexo",
       x="Sexo",
       y="Frecuencia") +
  theme_minimal()

grafico1

INTERPRETACIÓN

Analizar diferencias entre grupos.

11 PRUEBA CHI-CUADRADO

FÓRMULA

χ² = Σ ( (O_i − E_i)^2 / E_i )

Donde:

O_i = frecuencia observada
E_i = frecuencia esperada

chi <- chisq.test(tabla, correct = FALSE)
chi
## 
##  Pearson's Chi-squared test
## 
## data:  tabla
## X-squared = 5.2005, df = 1, p-value = 0.02258

Interpretación:


SEGUNDA BASE

Ejemplo1 <- read_sav("D:/6. CICIED/Lección 7/Ejemplo1.sav")
Tiempo <- Ejemplo1$Tiempo
Calif <- Ejemplo1$Calificación

grafico2 <- ggplot(Ejemplo1,aes(Tiempo,Calif))+
  geom_point(color="blue")+
  theme_minimal()

grafico2

12 PRUEBAS DE NORMALIDAD

Las pruebas evalúan si una variable sigue una distribución normal.


Shapiro-Wilk

FÓRMULA

W = ( (Σ a_i x_(i))² ) / Σ (x_i - x̄)²

Donde:

x_(i) = datos ordenados
x̄ = media muestral
a_i = coeficientes constantes

shapiro.test(Tiempo)
## 
##  Shapiro-Wilk normality test
## 
## data:  Tiempo
## W = 0.95077, p-value = 0.2815
shapiro.test(Calif)
## 
##  Shapiro-Wilk normality test
## 
## data:  Calif
## W = 0.9561, p-value = 0.3652

Kolmogorov-Smirnov

FÓRMULA

D = max |F_n(x) − F(x)|

Donde:

F_n(x) = distribución empírica
F(x) = distribución teórica

ks.test(Tiempo,"pnorm",mean(Tiempo),sd(Tiempo))
## Warning in ks.test.default(Tiempo, "pnorm", mean(Tiempo), sd(Tiempo)): ties
## should not be present for the one-sample Kolmogorov-Smirnov test
## 
##  Asymptotic one-sample Kolmogorov-Smirnov test
## 
## data:  Tiempo
## D = 0.10837, p-value = 0.9407
## alternative hypothesis: two-sided

Anderson-Darling

FÓRMULA

A² = -n - (1/n) Σ( (2i-1)[ln(F(x_i)) + ln(1-F(x_{n+1-i}))] )

ad.test(Tiempo)
## 
##  Anderson-Darling normality test
## 
## data:  Tiempo
## A = 0.45541, p-value = 0.2451
ad.test(Calif)
## 
##  Anderson-Darling normality test
## 
## data:  Calif
## A = 0.35682, p-value = 0.427

Asimetría

FÓRMULA

Skewness = E[(X − μ)^3] / σ^3

Donde:

μ = media
σ = desviación estándar

skewness(Tiempo)
## [1] 0.2812418
skewness(Calif)
## [1] 0.3442303

Curtosis

FÓRMULA

Kurtosis = E[(X − μ)^4] / σ^4

kurtosis(Tiempo)-3
## [1] -1.090299
kurtosis(Calif)-3
## [1] -0.8390218

13 CORRELACIÓN

Coeficiente de correlación de Pearson.

FÓRMULA

r = Σ[(x_i − x̄)(y_i − ȳ)] / √(Σ(x_i − x̄)² Σ(y_i − ȳ)²)

Donde:

x_i = observaciones variable X
y_i = observaciones variable Y

cor(Tiempo,Calif,method="pearson")
## [1] 0.7233087
cor(Tiempo,Calif,method="spearman")
## [1] 0.6700887
cor(Tiempo,Calif,method="kendall")
## [1] 0.4833916
cor.test(Tiempo,Calif,method="pearson")
## 
##  Pearson's product-moment correlation
## 
## data:  Tiempo and Calif
## t = 4.9131, df = 22, p-value = 6.504e-05
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.4517130 0.8722113
## sample estimates:
##       cor 
## 0.7233087

14 PARTICIÓN ENTRENAMIENTO Y PRUEBA

Se divide el dataset para evaluar el modelo.

set.seed(2026)

ind <- sample(2,nrow(Ejemplo1),replace=TRUE,prob=c(0.8,0.2))

train <- Ejemplo1[ind==1,]

test <- Ejemplo1[ind==2,]
head(train)
## # A tibble: 6 × 3
##      ID Tiempo Calificación
##   <dbl>  <dbl>        <dbl>
## 1     1    250            5
## 2     2    298           13
## 3     3    338            7
## 4     4    534           13
## 5     5    205           11
## 6     6    478           18

15 REGRESIÓN LINEAL SIMPLE

FÓRMULA

Y = β0 + β1X + ε

Donde:

Y = variable dependiente
X = variable independiente
β0 = intercepto
β1 = pendiente
ε = error

Tiempos <- train$Tiempo
Califs <- train$Calificación

modelo_train <- lm(Califs ~ Tiempos,data=train)

summary(modelo_train)
## 
## Call:
## lm(formula = Califs ~ Tiempos, data = train)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.6808 -2.4923  0.8794  1.9868  4.7824 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 4.279768   1.690841   2.531 0.019865 *  
## Tiempos     0.021604   0.004586   4.711 0.000134 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.815 on 20 degrees of freedom
## Multiple R-squared:  0.526,  Adjusted R-squared:  0.5023 
## F-statistic:  22.2 on 1 and 20 DF,  p-value: 0.0001338

16 PREDICCIONES

Tiempos <- test$Tiempo
Califs <- test$Calificación

pred <- predict(modelo_train,newdata=test)

real <- test$Calificación

data.frame(real,pred)
##   real      pred
## 1   12 15.211416
## 2    6  8.686994

17 ERROR CUADRÁTICO MEDIO

FÓRMULA

MSE = (1/n) Σ (y_i − ŷ_i)^2

Donde:

y_i = valor real
ŷ_i = valor predicho
n = número de observaciones

MSE <- mean((real-pred)^2)

MSE
## [1] 8.766566

INTERPRETACIÓN

Mientras menor sea el MSE, mejor es el modelo.


grafico4 <- ggplot(data.frame(real,pred),
                   aes(real,pred))+
  geom_point(color="darkgreen")+
  geom_abline(slope=1,intercept=0,color="red")

grafico4

CONCLUSIONES

En este análisis aprendimos: