library(readr)
# install.packages("rpart")
library(rpart)
# install.packages("rpart.plot")
library(rpart.plot)
## Warning: package 'rpart.plot' was built under R version 4.4.3
titanic <- read_csv("C:/Users/robie/Downloads/titanic (1).csv")
## Rows: 1310 Columns: 14
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (7): name, sex, ticket, cabin, embarked, boat, home.dest
## dbl (7): pclass, survived, age, sibsp, parch, fare, body
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Instalar paquetes y llamar librerías

# install.packages("rpart")
library(rpart)
# install.packages("rpart.plot")
library(rpart.plot)

Crear árbol de decisión

titanic <- titanic[,c("pclass","age","sex","survived")]
titanic$survived <- as.factor(titanic$survived)
titanic$pclass <- as.factor(titanic$pclass)
titanic$sex <- as.factor(titanic$sex)
str(titanic)
## tibble [1,310 × 4] (S3: tbl_df/tbl/data.frame)
##  $ pclass  : Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 1 1 ...
##  $ age     : num [1:1310] 29 0.917 2 30 25 ...
##  $ sex     : Factor w/ 2 levels "female","male": 1 2 1 2 1 2 1 2 1 2 ...
##  $ survived: Factor w/ 2 levels "0","1": 2 2 1 1 1 2 2 1 2 1 ...
arbol_titanic <- rpart(survived~., data=titanic)
rpart.plot(arbol_titanic)

prp(arbol_titanic, extra=7, prefix="fracción\n")

# Conclusiones En conclusión, las más altas probabilidades de sobrevivir en el naufragio del Titanic son: * 100%: Si eres niño varón menor de 9.5 años de 1° o 2° clase. * 73%: Si eres mujer. Y, por el contrario, las más bajas probabilidades de sobrevivir son: * 17%: Si eres hombre mayor a 9.5 años. * 38%: Si eres niño varón menor de 9.5 años de 3° clase.