library(ggmosaic)
## Loading required package: ggplot2
library(ggplot2)
library(fitdistrplus)
## Loading required package: MASS
## Loading required package: survival
library(MASS)
library(survival)
library(ggstatsplot)
## You can cite this package as:
## Patil, I. (2021). Visualizations with statistical details: The 'ggstatsplot' approach.
## Journal of Open Source Software, 6(61), 3167, doi:10.21105/joss.03167
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ lubridate 1.9.3 ✔ tibble 3.2.1
## ✔ purrr 1.0.2 ✔ tidyr 1.3.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ✖ dplyr::select() masks MASS::select()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(lubridate)
library(caTools)
library(ROCR)
Leemos el fichero de datos:
x = read.csv("hotel_bookings.csv", stringsAsFactors = TRUE)
dim(x) # Debería mostrar 119390 filas y 32 columnas en el dataset original
## [1] 119390 32
Primero inspeccionamos los datos:
## hotel is_canceled lead_time arrival_date_year
## City Hotel :79330 Min. :0.0000 Min. : 0 Min. :2015
## Resort Hotel:40060 1st Qu.:0.0000 1st Qu.: 18 1st Qu.:2016
## Median :0.0000 Median : 69 Median :2016
## Mean :0.3704 Mean :104 Mean :2016
## 3rd Qu.:1.0000 3rd Qu.:160 3rd Qu.:2017
## Max. :1.0000 Max. :737 Max. :2017
##
## arrival_date_month arrival_date_week_number arrival_date_day_of_month
## August :13877 Min. : 1.00 Min. : 1.0
## July :12661 1st Qu.:16.00 1st Qu.: 8.0
## May :11791 Median :28.00 Median :16.0
## October:11160 Mean :27.17 Mean :15.8
## April :11089 3rd Qu.:38.00 3rd Qu.:23.0
## June :10939 Max. :53.00 Max. :31.0
## (Other):47873
## stays_in_weekend_nights stays_in_week_nights adults
## Min. : 0.0000 Min. : 0.0 Min. : 0.000
## 1st Qu.: 0.0000 1st Qu.: 1.0 1st Qu.: 2.000
## Median : 1.0000 Median : 2.0 Median : 2.000
## Mean : 0.9276 Mean : 2.5 Mean : 1.856
## 3rd Qu.: 2.0000 3rd Qu.: 3.0 3rd Qu.: 2.000
## Max. :19.0000 Max. :50.0 Max. :55.000
##
## children babies meal country
## Min. : 0.0000 Min. : 0.000000 BB :92310 PRT :48590
## 1st Qu.: 0.0000 1st Qu.: 0.000000 FB : 798 GBR :12129
## Median : 0.0000 Median : 0.000000 HB :14463 FRA :10415
## Mean : 0.1039 Mean : 0.007949 SC :10650 ESP : 8568
## 3rd Qu.: 0.0000 3rd Qu.: 0.000000 Undefined: 1169 DEU : 7287
## Max. :10.0000 Max. :10.000000 ITA : 3766
## NA's :4 (Other):28635
## market_segment distribution_channel is_repeated_guest
## Online TA :56477 Corporate: 6677 Min. :0.00000
## Offline TA/TO:24219 Direct :14645 1st Qu.:0.00000
## Groups :19811 GDS : 193 Median :0.00000
## Direct :12606 TA/TO :97870 Mean :0.03191
## Corporate : 5295 Undefined: 5 3rd Qu.:0.00000
## Complementary: 743 Max. :1.00000
## (Other) : 239
## previous_cancellations previous_bookings_not_canceled reserved_room_type
## Min. : 0.00000 Min. : 0.0000 A :85994
## 1st Qu.: 0.00000 1st Qu.: 0.0000 D :19201
## Median : 0.00000 Median : 0.0000 E : 6535
## Mean : 0.08712 Mean : 0.1371 F : 2897
## 3rd Qu.: 0.00000 3rd Qu.: 0.0000 G : 2094
## Max. :26.00000 Max. :72.0000 B : 1118
## (Other): 1551
## assigned_room_type booking_changes deposit_type agent
## A :74053 Min. : 0.0000 No Deposit:104641 9 :31961
## D :25322 1st Qu.: 0.0000 Non Refund: 14587 NULL :16340
## E : 7806 Median : 0.0000 Refundable: 162 240 :13922
## F : 3751 Mean : 0.2211 1 : 7191
## G : 2553 3rd Qu.: 0.0000 14 : 3640
## C : 2375 Max. :21.0000 7 : 3539
## (Other): 3530 (Other):42797
## company days_in_waiting_list customer_type
## NULL :112593 Min. : 0.000 Contract : 4076
## 40 : 927 1st Qu.: 0.000 Group : 577
## 223 : 784 Median : 0.000 Transient :89613
## 67 : 267 Mean : 2.321 Transient-Party:25124
## 45 : 250 3rd Qu.: 0.000
## 153 : 215 Max. :391.000
## (Other): 4354
## adr required_car_parking_spaces total_of_special_requests
## Min. : -6.38 Min. :0.00000 Min. :0.0000
## 1st Qu.: 69.29 1st Qu.:0.00000 1st Qu.:0.0000
## Median : 94.58 Median :0.00000 Median :0.0000
## Mean : 101.83 Mean :0.06252 Mean :0.5714
## 3rd Qu.: 126.00 3rd Qu.:0.00000 3rd Qu.:1.0000
## Max. :5400.00 Max. :8.00000 Max. :5.0000
##
## reservation_status reservation_status_date
## Canceled :43017 2015-10-21: 1461
## Check-Out:75166 2015-07-06: 805
## No-Show : 1207 2016-11-25: 790
## 2015-01-01: 763
## 2016-01-18: 625
## 2015-07-02: 469
## (Other) :114477
Observamos valores extraños en adults,
children, babies y adr.
adults con valores hasta 55children con valores hasta 10babies con valores hasta 10adr con valores negativos o muy elevadosAnalizamos adults:
hist(x$adults, breaks=55, main="Histograma de Adults", xlab="Número de adultos")
plot(sort(x$adults), main="Valores Ordenados de Adults", xlab="Índice", ylab="Número de adultos")
grid()
table(x$adults)
##
## 0 1 2 3 4 5 6 10 20 26 27 40 50
## 403 23027 89680 6202 62 2 1 1 2 5 2 1 1
## 55
## 1
Eliminamos filas con adults >= 10:
x = x[x$adults < 10,]
Ejercicio (resuelto a modo de ejemplo): Hacer lo
mismo con children y babies:
# Children
plot(sort(x$children), main="Valores Ordenados de Children", xlab="Índice", ylab="Número de niños")
grid()
table(x$children)
##
## 0 1 2 3 10
## 110783 4861 3652 76 1
x = x[x$children < 10,]
# Babies
plot(sort(x$babies), main="Valores Ordenados de Babies", xlab="Índice", ylab="Número de bebés")
grid()
table(x$babies)
##
## 0 1 2 9 10
## 118455 900 15 1 1
x = x[x$babies < 10,]
Analizamos adr (precio medio diario):
plot(sort(x$adr), main="Valores Ordenados de ADR", xlab="Índice", ylab="ADR")
grid()
Eliminamos valores negativos y mayores o iguales a 1000:
x = x[x$adr >= 0 & x$adr < 1000,]
Dibujamos el histograma de adr:
ggplot(data=x, aes(x=adr)) +
geom_histogram(bins=55, colour="black", fill="lightgray") +
theme_light() +
labs(title="Histograma del Precio Medio Diario (ADR)",
x="ADR (Precio Medio Diario)",
y="Frecuencia")
## Warning: Removed 4 rows containing non-finite outside the scale range
## (`stat_bin()`).
Sustituimos NA en children por 0:
x[is.na(x$children), 'children'] = 0
Eliminamos estancias de 0 días, coste 0 y sin personas:
x = x[x$adr > 0 & (x$stays_in_week_nights + x$stays_in_weekend_nights) > 0 &
(x$adults + x$children + x$babies) > 0 & !is.na(x$children),]
Comprobamos la distribución del adr con
descdist():
# Verificar variación
unique_values <- unique(x$adr)
cat("Número de valores únicos en adr:", length(unique_values), "\n")
## Número de valores únicos en adr: 8863
# Si no hay variación suficiente, detenerse o ajustar el filtrado
if(length(unique_values) < 2){
cat("No hay suficiente variación en 'adr' para trazar el gráfico de descdist.\n")
} else {
# Limpiar NA e Inf
x <- x[!is.na(x$adr) & !is.infinite(x$adr), ]
# Intentar descdist sin gráfico
descdist(x$adr, boot=1000, graph=FALSE)
}
## summary statistics
## ------
## min: 0.26 max: 510
## median: 95
## mean: 103.4994
## estimated sd: 46.7001
## estimated skewness: 1.198425
## estimated kurtosis: 5.336871
(El gráfico Cullen y Frey se mostrará si existe variación suficiente
en adr.)
Analizamos la distribución del ADR según el tipo de hotel:
ggplot(data=x, aes(x=adr, fill=hotel)) +
geom_histogram(bins=50, colour="black") +
theme_light() +
labs(title="Distribución del ADR por Tipo de Hotel",
x="ADR",
y="Frecuencia",
fill="Tipo de Hotel")
Violin plot:
ggplot(data=x, aes(x=hotel, y=adr, fill=hotel)) +
geom_violin() +
geom_boxplot(width=.1, outliers=FALSE) +
coord_flip() +
theme_light() +
labs(title="ADR por Tipo de Hotel (Violin + Boxplot)",
x="Tipo de Hotel",
y="ADR")
Prueba estadística con ggstatsplot:
ggbetweenstats(data=x, x=hotel, y=adr)
Analizamos países con más de 100 reservas:
xx = x %>% group_by(country) %>% mutate(pais=n()) %>% filter(pais>=100)
xx$country = factor(xx$country)
ggplot(data=xx, aes(x=reorder(country, -pais))) +
geom_bar(stat="count", aes(fill=hotel)) +
theme_light() +
labs(title="Países con al menos 100 reservas",
x="País",
y="Número de Reservas",
fill="Tipo de Hotel") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
Creamos una variable para distinguir clientes de Portugal y extranjeros:
x$is_portugal = ifelse(x$country == "PRT", "Portugal", "Extranjero")
Análisis de cancelaciones:
x$is_canceled = as.factor(x$is_canceled)
ggplot(data=x) +
geom_mosaic(aes(x=product(is_canceled, hotel), fill=hotel)) +
theme_light() +
labs(title="Relación entre Cancelación y Tipo de Hotel")
## Warning: The `scale_name` argument of `continuous_scale()` is deprecated as of ggplot2
## 3.5.0.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: The `trans` argument of `continuous_scale()` is deprecated as of ggplot2 3.5.0.
## ℹ Please use the `transform` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: `unite_()` was deprecated in tidyr 1.2.0.
## ℹ Please use `unite()` instead.
## ℹ The deprecated feature was likely used in the ggmosaic package.
## Please report the issue at <https://github.com/haleyjeppson/ggmosaic>.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Países con al menos 1000 reservas:
xx = x %>% group_by(country) %>% mutate(pais=n()) %>% filter(pais>=1000)
xx$country = factor(xx$country)
ggplot(data=xx) +
geom_mosaic(aes(x=product(is_canceled, country), fill=country)) +
theme_light() +
labs(title="Relación entre Cancelación y País (>=1000 reservas)",
x="Cancelación",
y="País") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
Analizamos las reservas a lo largo del tiempo, creamos variable
dia:
x$dia = as.Date(paste0(x$arrival_date_year,'-',x$arrival_date_month,'-',x$arrival_date_day_of_month), "%Y-%B-%d")
ggplot(data=x, aes(x=dia, group=arrival_date_year, color=arrival_date_year)) +
geom_bar() +
theme_light() +
labs(title="Reservas a lo largo del tiempo",
x="Fecha",
y="Número de Reservas",
color="Año")
Definición arbitraria del tipo de viaje:
x$tipo = ifelse(x$stays_in_weekend_nights == 0, "work",
ifelse(x$stays_in_week_nights == 0, "weekend",
ifelse(x$stays_in_week_nights == 1 & wday(x$dia) == 6, "weekend",
ifelse(x$stays_in_week_nights == 5 & (x$stays_in_weekend_nights == 3 | x$stays_in_weekend_nights == 4), "package",
ifelse(x$stays_in_week_nights<=5 & x$stays_in_weekend_nights<3, "work+rest",
"rest")))))