library(tree)
## Warning: package 'tree' was built under R version 4.2.3
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(nycflights13)
head(weather)
## # A tibble: 6 × 15
##   origin  year month   day  hour  temp  dewp humid wind_dir wind_speed wind_gust
##   <chr>  <int> <int> <int> <int> <dbl> <dbl> <dbl>    <dbl>      <dbl>     <dbl>
## 1 EWR     2013     1     1     1  39.0  26.1  59.4      270      10.4         NA
## 2 EWR     2013     1     1     2  39.0  27.0  61.6      250       8.06        NA
## 3 EWR     2013     1     1     3  39.0  28.0  64.4      240      11.5         NA
## 4 EWR     2013     1     1     4  39.9  28.0  62.2      250      12.7         NA
## 5 EWR     2013     1     1     5  39.0  28.0  64.4      260      12.7         NA
## 6 EWR     2013     1     1     6  37.9  28.0  67.2      240      11.5         NA
## # … with 4 more variables: precip <dbl>, pressure <dbl>, visib <dbl>,
## #   time_hour <dttm>
weather <- select(weather,-(year:day),-(time_hour))
weather$origin <- as.factor(weather$origin)
head(weather)
## # A tibble: 6 × 11
##   origin  hour  temp  dewp humid wind_dir wind_sp…¹ wind_…² precip press…³ visib
##   <fct>  <int> <dbl> <dbl> <dbl>    <dbl>     <dbl>   <dbl>  <dbl>   <dbl> <dbl>
## 1 EWR        1  39.0  26.1  59.4      270     10.4       NA      0   1012     10
## 2 EWR        2  39.0  27.0  61.6      250      8.06      NA      0   1012.    10
## 3 EWR        3  39.0  28.0  64.4      240     11.5       NA      0   1012.    10
## 4 EWR        4  39.9  28.0  62.2      250     12.7       NA      0   1012.    10
## 5 EWR        5  39.0  28.0  64.4      260     12.7       NA      0   1012.    10
## 6 EWR        6  37.9  28.0  67.2      240     11.5       NA      0   1012.    10
## # … with abbreviated variable names ¹​wind_speed, ²​wind_gust, ³​pressure
train=sample(seq(length(weather$origin)),length(weather$origin)*0.7,replace=FALSE)

Creación del árbol

#Arbol basado en las especies
weather.tree = tree::tree(weather$origin~.,weather,subset=train)
summary(weather.tree)
## 
## Classification tree:
## tree::tree(formula = weather$origin ~ ., data = weather, subset = train)
## Variables actually used in tree construction:
## [1] "wind_speed"
## Number of terminal nodes:  2 
## Residual mean deviance:  2.127 = 7366 / 3463 
## Misclassification error rate: 0.5971 = 2069 / 3465
plot(weather.tree);text(weather.tree,pretty=0)

Ver los valores del árbol

weather.tree
## node), split, n, deviance, yval, (yprob)
##       * denotes terminal node
## 
## 1) root 3465 7567 LGA ( 0.3411 0.2831 0.3758 )  
##   2) wind_speed < 16.6863 1803 3758 EWR ( 0.4132 0.1830 0.4038 ) *
##   3) wind_speed > 16.6863 1662 3608 JFK ( 0.2629 0.3917 0.3454 ) *

Predecir el otro 30% de los datos

# Crear el conjunto de datos de prueba
test_indices <- sample(seq(length(weather$origin)), length(weather$origin) * 0.30, replace = FALSE)
nuevos_datos <- weather[test_indices, ]

# Realiza predicciones con el modelo de árbol de decisión
predicciones <- predict(weather.tree, nuevos_datos, type = "class")

# Imprime las predicciones
summary(predicciones)
##  EWR  JFK  LGA 
## 6799 1035    0

Matriz de confusion

# Crear la matriz de confusión solo si hay observaciones en el conjunto de prueba
if (length(test_indices) > 0) {
  # Obtener las clases reales del conjunto de prueba
  clases_reales <- weather$origin[test_indices]

  # Crear la matriz de confusión
  matriz_confusion <- table(ClaseReal = clases_reales, ClasePredicha = predicciones)

  # Imprimir la matriz de confusión
  print(matriz_confusion)
} else {
  cat("No hay observaciones en el conjunto de prueba.")
}
##          ClasePredicha
## ClaseReal  EWR  JFK  LGA
##       EWR 2386  225    0
##       JFK 2173  461    0
##       LGA 2240  349    0
# Valores de la matriz de confusión
a <- 1398  # Verdaderos positivos para EWR
b <- 191   # Falsos positivos para JFK cuando la clase real es EWR
c <- 1061  # Falsos positivos para LGA cuando la clase real es EWR
d <- 1233  # Falsos positivos para EWR cuando la clase real es JFK
e <- 367   # Verdaderos positivos para JFK
f <- 1005  # Falsos positivos para LGA cuando la clase real es JFK
g <- 1347  # Falsos positivos para EWR cuando la clase real es LGA
h <- 270   # Falsos positivos para JFK cuando la clase real es LGA
i <- 962   # Verdaderos positivos para LGA

# Cálculo de los porcentajes de error
error_EWR <- (b + c) / (a + b + c) * 100
error_JFK <- (d + f) / (a + d + f) * 100
error_LGA <- (g + h) / (a + g + h) * 100

# Imprimir los resultados
cat("Error de EWR:", round(error_EWR, 2), "%\n")
## Error de EWR: 47.25 %
cat("Error de JFK:", round(error_JFK, 2), "%\n")
## Error de JFK: 61.55 %
cat("Error de LGA:", round(error_LGA, 2), "%\n")
## Error de LGA: 53.63 %