Francisco Guijarro

Universidad Politécnica de Valencia

Creative Commons Attribution 4.0 International License (CC BY 4.0)

1 Análisis de datos

Este capítulo servirá para desarrollar un ejemplo completo de analítica de datos, aplicando los conocimientos adquiridos en los capítulos anteriores.

Para ello utilizaremos una base de datos con informaión sobre reservas en el popular portal airbnb.

Deberás descargar el archivo “airbnb_seattle.csv” y leerlo con el siguiente código. Tendrás que sustituir la ruta por aquella en la que has descargado el fichero. Sólo trabajaremos con algunas de las variables de dicho archivo:

library(dplyr)
airbnb <- read.csv("./../Datos/airbnb_seattle.csv")
variables <- c("id", "host_id", "host_name", "host_since", "host_response_time",
               "host_response_rate", "host_acceptance_rate", "host_is_superhost",
               "neighbourhood_group_cleansed", "host_total_listings_count", 
               "host_has_profile_pic", "latitude", "longitude",
               "is_location_exact", "property_type",
               "room_type", "accommodates", "bathrooms", "bedrooms", "beds",
               "bed_type", "amenities", "price", "weekly_price", "monthly_price",
               "security_deposit", "cleaning_fee", "guests_included", "extra_people",
               "minimum_nights", "maximum_nights", "calendar_updated",
               "availability_30", "availability_60", "availability_90", "availability_365",
               "number_of_reviews", "review_scores_rating", "review_scores_accuracy",
               "review_scores_cleanliness", "review_scores_checkin", 
               "review_scores_communication", "review_scores_location", 
               "review_scores_value", "cancellation_policy", "reviews_per_month")
airbnb <- airbnb %>%
  select(variables)
str(airbnb)
## 'data.frame':    3818 obs. of  46 variables:
##  $ id                          : int  241032 953595 3308979 7421966 278830 5956968 1909058 856550 4948745 2493658 ...
##  $ host_id                     : int  956883 5177328 16708587 9851441 1452570 326758 2497928 4016632 2166277 5177328 ...
##  $ host_name                   : chr  "Maija" "Andrea" "Jill" "Emily" ...
##  $ host_since                  : chr  "2011-08-11" "2013-02-21" "2014-06-12" "2013-11-06" ...
##  $ host_response_time          : chr  "within a few hours" "within an hour" "within a few hours" "N/A" ...
##  $ host_response_rate          : chr  "96%" "98%" "67%" "N/A" ...
##  $ host_acceptance_rate        : chr  "100%" "100%" "100%" "N/A" ...
##  $ host_is_superhost           : chr  "f" "t" "f" "f" ...
##  $ neighbourhood_group_cleansed: chr  "Queen Anne" "Queen Anne" "Queen Anne" "Queen Anne" ...
##  $ host_total_listings_count   : int  3 6 2 1 2 1 1 5 1 6 ...
##  $ host_has_profile_pic        : chr  "t" "t" "t" "t" ...
##  $ latitude                    : num  47.6 47.6 47.6 47.6 47.6 ...
##  $ longitude                   : num  -122 -122 -122 -122 -122 ...
##  $ is_location_exact           : chr  "t" "t" "t" "t" ...
##  $ property_type               : chr  "Apartment" "Apartment" "House" "Apartment" ...
##  $ room_type                   : chr  "Entire home/apt" "Entire home/apt" "Entire home/apt" "Entire home/apt" ...
##  $ accommodates                : int  4 4 11 3 6 2 2 2 2 4 ...
##  $ bathrooms                   : num  1 1 4.5 1 2 1 1 1 1 1 ...
##  $ bedrooms                    : int  1 1 5 0 3 1 1 1 1 1 ...
##  $ beds                        : int  1 1 7 2 3 1 1 1 1 1 ...
##  $ bed_type                    : chr  "Real Bed" "Real Bed" "Real Bed" "Real Bed" ...
##  $ amenities                   : chr  "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,Heating,\"Family/Kid Friendly\",Washer,Dryer}" "{TV,Internet,\"Wireless Internet\",Kitchen,\"Free Parking on Premises\",\"Buzzer/Wireless Intercom\",Heating,\""| __truncated__ "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,\"Free Parking on Premises\",\"Pet"| __truncated__ "{Internet,\"Wireless Internet\",Kitchen,\"Indoor Fireplace\",Heating,\"Family/Kid Friendly\",Washer,Dryer,\"Smo"| __truncated__ ...
##  $ price                       : chr  "$85.00" "$150.00" "$975.00" "$100.00" ...
##  $ weekly_price                : chr  "" "$1,000.00" "" "$650.00" ...
##  $ monthly_price               : chr  "" "$3,000.00" "" "$2,300.00" ...
##  $ security_deposit            : chr  "" "$100.00" "$1,000.00" "" ...
##  $ cleaning_fee                : chr  "" "$40.00" "$300.00" "" ...
##  $ guests_included             : int  2 1 10 1 6 1 1 1 1 1 ...
##  $ extra_people                : chr  "$5.00" "$0.00" "$25.00" "$0.00" ...
##  $ minimum_nights              : int  1 2 4 1 1 1 3 2 3 2 ...
##  $ maximum_nights              : int  365 90 30 1125 1125 6 14 7 1125 365 ...
##  $ calendar_updated            : chr  "4 weeks ago" "today" "5 weeks ago" "6 months ago" ...
##  $ availability_30             : int  14 13 1 0 30 0 20 22 6 6 ...
##  $ availability_60             : int  41 13 6 0 60 0 49 42 36 19 ...
##  $ availability_90             : int  71 16 17 0 90 27 71 42 66 49 ...
##  $ availability_365            : int  346 291 220 143 365 302 346 100 341 324 ...
##  $ number_of_reviews           : int  207 43 20 0 38 17 58 173 8 32 ...
##  $ review_scores_rating        : int  95 96 97 NA 92 95 99 97 97 97 ...
##  $ review_scores_accuracy      : int  10 10 10 NA 9 10 10 10 10 10 ...
##  $ review_scores_cleanliness   : int  10 10 10 NA 9 10 10 10 9 10 ...
##  $ review_scores_checkin       : int  10 10 10 NA 10 10 10 10 10 10 ...
##  $ review_scores_communication : int  10 10 10 NA 10 10 10 10 9 10 ...
##  $ review_scores_location      : int  9 10 10 NA 9 10 10 9 10 10 ...
##  $ review_scores_value         : int  10 10 10 NA 9 10 10 10 10 9 ...
##  $ cancellation_policy         : chr  "moderate" "strict" "strict" "flexible" ...
##  $ reviews_per_month           : num  4.07 1.48 1.15 NA 0.89 2.45 2.46 4.73 1.22 1.55 ...

Imagen de los anuncios de AirBnB en Seattle (septiembre de 2020)

A continuación aparece una descripción de los diferentes campos que componen esta fuente de datos:

  • id: Número identificador del alojamiento.

  • host_id: Identificador del anunciante. Ten en cuenta que un mismo anunciante puede tener varios alojamientos.

  • host_name: Nombre del anfitrión.

  • host_since: fecha de alta del anfitrión.

  • host_response_time: tiempo que suele tomar el anfitrión en responder.

  • host_response_rate: tasa de respuesta del anfitrión.

  • host_acceptance_rate: tasa de aceptación del anfitrión.

  • host_is_superhost: variable que indica si el anfitrión es un superhost.

  • neighbourhood_group_cleansed: distrito.

  • host_total_listings_count: número total de alojamientos del anfitrión (algunos en varias ciudades).

  • host_has_profile_pic: variable binaria que indica si el anfitrión tiene foto de perfil.

  • latitude: coordenadas con la latitud.

  • longitude: coordenadas con la longitud.

  • is_location_exact: varible binaria que indica si en el anuncio se proporciona la dirección exacta del alojamiento.

  • property_type: tipo de alojamiento.

  • room_type: clasificación que airbnb hace del alojamiento.

  • accommodates: número de personas que se pueden alojar.

  • bathrooms: número de cuartos de baño.

  • bedrooms: número de habitaciones.

  • beds: número de camas.

  • bed_type: tipo de cama.

  • amenities: servicios que incluye el alojamiento.

  • price: precio por noche.

  • weekly_price: precio reducido para estancias semanales.

  • monthly_price: precio reducido para estancias mensuales.

  • security_deposit: el depósito a realizar en caso de reserva.

  • cleaning_fee: coste de la limpieza a asumir por el cliente.

  • guests_included: máximo número de huéspedes.

  • extra_people: coste por inquilino adicional.

  • minimum_nights: número mínimo de noches a contratar.

  • maximim_nights: número máximo de noches a contratar.

  • calendar_updated: última actualiación realizada en el calendario.

  • availability_30: disponibilidad en los próximos 30 días.

  • availability_60: disponibilidad en los próximos 60 días.

  • availability_90: disponibilidad en los próximos 90 días.

  • availability_365: disponibilidad en los próximos 365 días.

  • number_of_reviews: número de opiniones.

  • review_scores_rating: rating obtenidos en las opiniones de los clientes.

  • review_scores_accurary: rating sobre veracidad de los datos.

  • review_scores_cleanliness: rating sobre limpieza.

  • review_scores_checkin: rating sobre llegada.

  • review_scores_communication: rating sobre comunicación.

  • review_scores_location: rating sobre ubicación.

  • review_scores_value: rating sobre calidad.

  • cancellation_policy: política de cancelación.

  • reviews_per_month: número de opiniones promedio por mes.

Antes de pasar a los ejercicios, vamos a realizar algunos cambios en los tipos de varias variables. Por ejemplo, podemos ver que mientras el campo longitude es numérico, el campo latitude es de tipo carácter. Corregimos éstas y otras cuestiones de formato:

airbnb <- airbnb %>%
  mutate(host_since = as.Date(host_since, "%Y-%m-%d"),
         host_response_time = as.factor(host_response_time),
         host_response_rate = as.numeric(sub("%", "", host_response_rate))/100,
         host_acceptance_rate = as.numeric(sub("%", "", host_acceptance_rate))/100,
         host_is_superhost = as.logical(toupper(host_is_superhost)),
         neighbourhood_group_cleansed = as.factor(neighbourhood_group_cleansed),
         host_has_profile_pic = as.logical(toupper(host_has_profile_pic)),
         is_location_exact = as.logical(toupper(is_location_exact)),
         property_type = as.factor(property_type),
         room_type = as.factor(room_type),
         bed_type = as.factor(bed_type),
         price = as.numeric(sub("[$]", "", price)),
         weekly_price = as.numeric(sub("[$]", "", weekly_price)),
         monthly_price = as.numeric(sub("[$]", "", monthly_price)),
         security_deposit = as.numeric(sub("[$]", "", security_deposit)),
         cleaning_fee = as.numeric(sub("[$]", "", cleaning_fee)),
         extra_people = as.numeric(sub("[$]", "", extra_people)),
         calendar_updated = as.factor(calendar_updated),
         cancellation_policy = as.factor(cancellation_policy))
str(airbnb)
## 'data.frame':    3818 obs. of  46 variables:
##  $ id                          : int  241032 953595 3308979 7421966 278830 5956968 1909058 856550 4948745 2493658 ...
##  $ host_id                     : int  956883 5177328 16708587 9851441 1452570 326758 2497928 4016632 2166277 5177328 ...
##  $ host_name                   : chr  "Maija" "Andrea" "Jill" "Emily" ...
##  $ host_since                  : Date, format: "2011-08-11" "2013-02-21" ...
##  $ host_response_time          : Factor w/ 6 levels "","a few days or more",..: 5 6 5 3 6 3 6 6 3 6 ...
##  $ host_response_rate          : num  0.96 0.98 0.67 NA 1 NA 1 1 NA 0.98 ...
##  $ host_acceptance_rate        : num  1 1 1 NA NA NA 1 1 1 1 ...
##  $ host_is_superhost           : logi  FALSE TRUE FALSE FALSE FALSE FALSE ...
##  $ neighbourhood_group_cleansed: Factor w/ 17 levels "Ballard","Beacon Hill",..: 13 13 13 13 13 13 13 13 13 13 ...
##  $ host_total_listings_count   : int  3 6 2 1 2 1 1 5 1 6 ...
##  $ host_has_profile_pic        : logi  TRUE TRUE TRUE TRUE TRUE TRUE ...
##  $ latitude                    : num  47.6 47.6 47.6 47.6 47.6 ...
##  $ longitude                   : num  -122 -122 -122 -122 -122 ...
##  $ is_location_exact           : logi  TRUE TRUE TRUE TRUE TRUE TRUE ...
##  $ property_type               : Factor w/ 17 levels "","Apartment",..: 2 2 11 2 11 11 11 6 2 2 ...
##  $ room_type                   : Factor w/ 3 levels "Entire home/apt",..: 1 1 1 1 1 2 2 2 2 1 ...
##  $ accommodates                : int  4 4 11 3 6 2 2 2 2 4 ...
##  $ bathrooms                   : num  1 1 4.5 1 2 1 1 1 1 1 ...
##  $ bedrooms                    : int  1 1 5 0 3 1 1 1 1 1 ...
##  $ beds                        : int  1 1 7 2 3 1 1 1 1 1 ...
##  $ bed_type                    : Factor w/ 5 levels "Airbed","Couch",..: 5 5 5 5 5 5 5 5 5 5 ...
##  $ amenities                   : chr  "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,Heating,\"Family/Kid Friendly\",Washer,Dryer}" "{TV,Internet,\"Wireless Internet\",Kitchen,\"Free Parking on Premises\",\"Buzzer/Wireless Intercom\",Heating,\""| __truncated__ "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,\"Free Parking on Premises\",\"Pet"| __truncated__ "{Internet,\"Wireless Internet\",Kitchen,\"Indoor Fireplace\",Heating,\"Family/Kid Friendly\",Washer,Dryer,\"Smo"| __truncated__ ...
##  $ price                       : num  85 150 975 100 450 120 80 60 90 150 ...
##  $ weekly_price                : num  NA NA NA 650 NA 800 575 360 500 NA ...
##  $ monthly_price               : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ security_deposit            : num  NA 100 NA NA 700 NA 150 150 NA 100 ...
##  $ cleaning_fee                : num  NA 40 300 NA 125 40 NA 25 NA 40 ...
##  $ guests_included             : int  2 1 10 1 6 1 1 1 1 1 ...
##  $ extra_people                : num  5 0 25 0 15 30 10 0 0 0 ...
##  $ minimum_nights              : int  1 2 4 1 1 1 3 2 3 2 ...
##  $ maximum_nights              : int  365 90 30 1125 1125 6 14 7 1125 365 ...
##  $ calendar_updated            : Factor w/ 34 levels "1 week ago","10 months ago",..: 20 33 23 25 28 12 23 34 22 33 ...
##  $ availability_30             : int  14 13 1 0 30 0 20 22 6 6 ...
##  $ availability_60             : int  41 13 6 0 60 0 49 42 36 19 ...
##  $ availability_90             : int  71 16 17 0 90 27 71 42 66 49 ...
##  $ availability_365            : int  346 291 220 143 365 302 346 100 341 324 ...
##  $ number_of_reviews           : int  207 43 20 0 38 17 58 173 8 32 ...
##  $ review_scores_rating        : int  95 96 97 NA 92 95 99 97 97 97 ...
##  $ review_scores_accuracy      : int  10 10 10 NA 9 10 10 10 10 10 ...
##  $ review_scores_cleanliness   : int  10 10 10 NA 9 10 10 10 9 10 ...
##  $ review_scores_checkin       : int  10 10 10 NA 10 10 10 10 10 10 ...
##  $ review_scores_communication : int  10 10 10 NA 10 10 10 10 9 10 ...
##  $ review_scores_location      : int  9 10 10 NA 9 10 10 9 10 10 ...
##  $ review_scores_value         : int  10 10 10 NA 9 10 10 10 10 9 ...
##  $ cancellation_policy         : Factor w/ 3 levels "flexible","moderate",..: 2 3 3 1 3 3 2 3 3 3 ...
##  $ reviews_per_month           : num  4.07 1.48 1.15 NA 0.89 2.45 2.46 4.73 1.22 1.55 ...

Cuestión aparte merecen los servicios incluidos en el alojamiento, los amenities:

head(airbnb$amenities)
## [1] "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,Heating,\"Family/Kid Friendly\",Washer,Dryer}"                                                                                                                                                                                               
## [2] "{TV,Internet,\"Wireless Internet\",Kitchen,\"Free Parking on Premises\",\"Buzzer/Wireless Intercom\",Heating,\"Family/Kid Friendly\",Washer,Dryer,\"Smoke Detector\",\"Carbon Monoxide Detector\",\"First Aid Kit\",\"Safety Card\",\"Fire Extinguisher\",Essentials}"                                                    
## [3] "{TV,\"Cable TV\",Internet,\"Wireless Internet\",\"Air Conditioning\",Kitchen,\"Free Parking on Premises\",\"Pets Allowed\",\"Pets live on this property\",Dog(s),Cat(s),\"Hot Tub\",\"Indoor Fireplace\",Heating,\"Family/Kid Friendly\",Washer,Dryer,\"Smoke Detector\",\"Carbon Monoxide Detector\",Essentials,Shampoo}"
## [4] "{Internet,\"Wireless Internet\",Kitchen,\"Indoor Fireplace\",Heating,\"Family/Kid Friendly\",Washer,Dryer,\"Smoke Detector\",\"Carbon Monoxide Detector\",\"Safety Card\",\"Fire Extinguisher\",Essentials,Shampoo}"                                                                                                      
## [5] "{TV,\"Cable TV\",Internet,\"Wireless Internet\",Kitchen,Heating,\"Family/Kid Friendly\",\"Smoke Detector\",\"Carbon Monoxide Detector\",\"First Aid Kit\",\"Fire Extinguisher\",Essentials,Shampoo}"                                                                                                                      
## [6] "{\"Wireless Internet\",\"Free Parking on Premises\",Heating,\"Smoke Detector\",Essentials,Shampoo}"

Vemos que en esta variable se incluyen diferentes servicios, que cada alojamiento puede ofertar un número muy variado de los mismos. El problema es que dicha información no viene de forma estructurada. Es decir, no tenemos una variable que nos indique si el alojamiento incluye TV (TRUE) o no (FALSE); y lo mismo con el resto de amenities.

Esto obliga a tratar de forma diferente a esta variable, para poder extraer la máxima información de la misma que nos facilite su posterior inclusión en el análisis de los datos.

En primer lugar, cambiaremos el formato de la variable, eliminando todos los signos de puntuación que dificultad la lectura de los datos. Paa ello utilizaremos la función str_replace_all de la librería stringr:

library(stringr)
airbnb <- airbnb %>%
  mutate(amenities = str_replace_all(amenities, "[[:punct:]]", " "))
head(airbnb$amenities)
## [1] " TV  Cable TV  Internet  Wireless Internet   Air Conditioning  Kitchen Heating  Family Kid Friendly  Washer Dryer "                                                                                                                                                                                 
## [2] " TV Internet  Wireless Internet  Kitchen  Free Parking on Premises   Buzzer Wireless Intercom  Heating  Family Kid Friendly  Washer Dryer  Smoke Detector   Carbon Monoxide Detector   First Aid Kit   Safety Card   Fire Extinguisher  Essentials "                                                
## [3] " TV  Cable TV  Internet  Wireless Internet   Air Conditioning  Kitchen  Free Parking on Premises   Pets Allowed   Pets live on this property  Dog s  Cat s   Hot Tub   Indoor Fireplace  Heating  Family Kid Friendly  Washer Dryer  Smoke Detector   Carbon Monoxide Detector  Essentials Shampoo "
## [4] " Internet  Wireless Internet  Kitchen  Indoor Fireplace  Heating  Family Kid Friendly  Washer Dryer  Smoke Detector   Carbon Monoxide Detector   Safety Card   Fire Extinguisher  Essentials Shampoo "                                                                                              
## [5] " TV  Cable TV  Internet  Wireless Internet  Kitchen Heating  Family Kid Friendly   Smoke Detector   Carbon Monoxide Detector   First Aid Kit   Fire Extinguisher  Essentials Shampoo "                                                                                                              
## [6] "  Wireless Internet   Free Parking on Premises  Heating  Smoke Detector  Essentials Shampoo "

Una vez limpiado el campo amenities, vamos a crear una nueva variable por cada servicio que pueda ser de nuestro interés para un análisis posterior:

airbnb <- airbnb %>%
  mutate(tv = str_detect(amenities, "TV"),
         internet = str_detect(amenities, "Internet"),
         free_parking = str_detect(amenities, "Free Parking"),
         air_conditioning = str_detect(amenities, "Air Conditioning"),
         heating = str_detect(amenities, "Heating"),
         pets_allowed = str_detect(amenities, "Pets"),
         breakfast = str_detect(amenities, "Breakfast"),
         smoke_detector = str_detect(amenities, "Smoke Detector"),
         kitchen = str_detect(amenities, "Kitchen"),
         washer = str_detect(amenities, "Washer"),
         dryer = str_detect(amenities, "Dryer"))

2 Ejercicios

Resolver los siguientes ejercicios. Para ello, además de implementar el código necesario, también tendrás que comentar los resultados.

Ejercicio 1

¿Cuántas observaciones y cuántas columnas contienen los datos de airbnb?

nrow(airbnb)
## [1] 3818
ncol(airbnb)
## [1] 57

Ejercicio 2

Calcula la matriz de correlaciones entre las variables amenities creadas anteriormente. ¿Alguna correlación importante? ¿Qué implica que las variables washer y dryer tengan una correlación alta? ¿Por qué la correlación entre tv e internet es baja? En la respuesta puede ayudar los resultados de una table de contingencia entre ambas variables. Calcula qué porcentaje de alojamientos con televisión tienen también internet; y qué porcentaje de alojamientos con internet tienen adicionalmente televisión.

##                            tv   internet free_parking air_conditioning
## tv                1.000000000 0.19045670   0.10253563       0.16910503
## internet          0.190456695 1.00000000   0.11398298       0.06657210
## free_parking      0.102535634 0.11398298   1.00000000      -0.01280130
## air_conditioning  0.169105027 0.06657210  -0.01280130       1.00000000
## heating           0.155175118 0.32751325   0.14649675       0.07822640
## pets_allowed      0.008532814 0.06228141   0.16002035      -0.03910772
## breakfast        -0.069999690 0.03648732   0.03155173       0.01912572
## smoke_detector    0.129777519 0.19938390   0.09091880       0.06355351
## kitchen           0.190295416 0.20202197   0.04373139       0.08790672
## washer            0.156898040 0.16643483   0.10119991       0.07238905
## dryer             0.168710298 0.18059311   0.10848023       0.07750894
##                     heating pets_allowed   breakfast smoke_detector     kitchen
## tv               0.15517512  0.008532814 -0.06999969     0.12977752  0.19029542
## internet         0.32751325  0.062281414  0.03648732     0.19938390  0.20202197
## free_parking     0.14649675  0.160020349  0.03155173     0.09091880  0.04373139
## air_conditioning 0.07822640 -0.039107718  0.01912572     0.06355351  0.08790672
## heating          1.00000000  0.066421272  0.02516432     0.22164433  0.25342337
## pets_allowed     0.06642127  1.000000000  0.05547015     0.02520362 -0.04862208
## breakfast        0.02516432  0.055470146  1.00000000     0.02819050 -0.02882558
## smoke_detector   0.22164433  0.025203620  0.02819050     1.00000000  0.12972830
## kitchen          0.25342337 -0.048622083 -0.02882558     0.12972830  1.00000000
## washer           0.17413720 -0.015311453 -0.03126992     0.09847966  0.31443242
## dryer            0.20070179  0.000808285 -0.02377980     0.12624026  0.29531250
##                       washer        dryer
## tv                0.15689804  0.168710298
## internet          0.16643483  0.180593108
## free_parking      0.10119991  0.108480226
## air_conditioning  0.07238905  0.077508937
## heating           0.17413720  0.200701786
## pets_allowed     -0.01531145  0.000808285
## breakfast        -0.03126992 -0.023779803
## smoke_detector    0.09847966  0.126240258
## kitchen           0.31443242  0.295312499
## washer            1.00000000  0.872130144
## dryer             0.87213014  1.000000000
##        internet
## tv      FALSE TRUE
##   FALSE    94  983
##   TRUE     32 2709

Ejercicio 3

Haz un análisis similar al del ejercicio anterior detallando la relación entre kitchen, washer y dryer

## , , dryer = FALSE
## 
##        washer
## kitchen FALSE TRUE
##   FALSE   204    2
##   TRUE    480   18
## 
## , , dryer = TRUE
## 
##        washer
## kitchen FALSE TRUE
##   FALSE    32  157
##   TRUE    110 2815

Ejercicio 4

Dibujar en un gráfico de dispersión la latitud y longitud de los alojamientos, comparando el resultado con la imagen de Seattle incluida al principio del capítulo.

plot(airbnb$longitude, airbnb$latitude)
library(ggplot2)

ggplot(airbnb, aes(x = longitude, y = latitude)) +
  geom_point() + 
  geom_density_2d() +
  geom_density_2d_filled(alpha = 0.5)

Ejercicio 5

Un mismo anfitrión puede ofertar más de un alojamiento. Determinar el número de anfitriones diferentes según la variable host_id. Hacer una tabla de frecuencias con el número de alojamientos por anfitrión.

length(unique(airbnb$host_id))
## [1] 2751
## 
##    1    2    3    4    5    6    7    8    9   10   11   12   16   18   21   33 
## 2285  297   85   38   18    5    3    1    3    3    2    2    1    1    1    1 
##   34   36   37   39   46 
##    1    1    1    1    1

Ejercicio 6

El negocio de AirBnB ha crecido mucho en los últimos años. Obtener un histograma que refleje la evolución de altas de anfitriones.

library(lubridate)
anys <- year(airbnb$host_since)
summary(anys)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    2008    2012    2013    2013    2015    2016       2
n_anys <- length(unique(anys))
table(anys)
## anys
## 2008 2009 2010 2011 2012 2013 2014 2015 2016 
##    4   64  149  398  539  776  900  981    5
hist(anys)

Ejercicio 7

Ahora analicemos la evolución de los precios. Calcula el precio medio de los apartamentos por año y represéntalo gráficamente. Para ello puedes apoarte en la librería dplyr, y en sus funciones mutate, group_by y summarize.

## # A tibble: 10 x 2
##     anys media
##    <dbl> <dbl>
##  1  2008  79.5
##  2  2009 126. 
##  3  2010 144. 
##  4  2011 138. 
##  5  2012 125. 
##  6  2013 130. 
##  7  2014 127. 
##  8  2015 122. 
##  9  2016  53.2
## 10    NA 174.

Ejercicio 8

Analicemos el precio según otras variables. Representa la variable price frente a room_type en un diagrama de caja.

Ejercicio 9

La variable room_type es de tipo factor. Si realizamos el mismo ejercicio sustituyendo room_type por beds, que es una variables numérica, los resultados no serán los esperados. Deberás realizar un diagrama de caja pero adaptando la variable beds de numérica a factor. Comenta los resultados. ¿Cuál puede ser el motivo de que el precio aumente con el número de camas, pero la tendencia sea más dispersa a partir de 8 habitaciones?

Ejercicio 10

¿Está el precio del alojamiento relacionado con el barrio (neighbourhood_group_cleansed) donde se sitúa? ¿Cuáles son los barrios más caros en promedio? Calcula la correlación entre el precio medio por barrio y el número de alojamientos en cada barrio. ¿Se ubican más alojamientos en los barrios más caros, y menos en los menos económicos? Para el segundo gráfic del precio frente al barrio, añade la función coord_flip.

## # A tibble: 17 x 3
##    neighbourhood_group_cleansed precio_medio n_alojamientos
##    <fct>                               <dbl>          <int>
##  1 Magnolia                            178.              61
##  2 Queen Anne                          157.             295
##  3 Downtown                            154.             530
##  4 West Seattle                        141.             203
##  5 Cascade                             140.              89
##  6 Capitol Hill                        131.             567
##  7 Central Area                        128.             369
##  8 Ballard                             125.             230
##  9 Other neighborhoods                 119.             794
## 10 Interbay                            110.              11
## 11 Seward Park                         108.              44
## 12 Beacon Hill                          94.7            118
## 13 University District                  93.6            122
## 14 Lake City                            92.7             67
## 15 Rainier Valley                       91.9            159
## 16 Northgate                            88.6             80
## 17 Delridge                             83.3             79
##                precio_medio n_alojamientos
## precio_medio      1.0000000      0.3098646
## n_alojamientos    0.3098646      1.0000000

Ejercicio 11

Obtener un gráfico de barras sobre el tiempo de respuesta medio de los anfitriones (host_response_time). ¿Suelen responder rápido a las preguntas de los intersados?

library(ggplot2)
ggplot(airbnb, aes(x=host_response_time)) +
  geom_bar()

Ejercicio 12

Obtén la estadística de cuántos anfitriones reciben la califcación de super host, host_is_superhost. ¿Está relacionada esta variable con el tiempo de respuesta medio (host_response_time)? Haz una tabla de contingencia entre ambas variables y comenta los resultados.

## 
## FALSE  TRUE 
##  3038   778
##                  host_response_time
## host_is_superhost within an hour within a few hours within a day
##             FALSE           1203                770          540
##             TRUE             489                198           57
##                  host_response_time
## host_is_superhost a few days or more
##             FALSE                 37
##             TRUE                   1

Ejercicio 13

Con la ayuda de la librería dplyry sus funciones select, group_byy summarise, calcula el número medio de evaluaciones (reviews) recibidas para los superhosts y el resto de anfitriones. En la siguiente tabla, la fila con etiqueta TRUE se corresponde con los superhosts, mientras que el resto de anfitriones está en la fila FALSE. ¿A mayor número de evaluaciones recibidas, mayor probabilidad de que AirBnb te califique como superhost?:

## # A tibble: 3 x 2
##   host_is_superhost media
##   <lgl>             <dbl>
## 1 FALSE              17.2
## 2 TRUE               41.8
## 3 NA                  0

Ejercicio 14

A través de un análisis Chi-cuadrado (\(\chi^2\)), estima si las diferencias en el número de evaluaciones son estadísticamente significativas:

## 
##  Pearson's Chi-squared test
## 
## data:  table(airbnb$host_is_superhost, airbnb$number_of_reviews)
## X-squared = 833.03, df = 194, p-value < 2.2e-16

Ejercicio 15

Obtén un histograma donde se represente la distribución del número de evaluaciones de las dos poblaciones: superhost y el resto. Analizando el resultado, parece evidente que son distribuciones distintas; esto es, que se constata el resultado del análisis Chi-cuadrado.

library(ggplot2)
ggplot(airbnb, aes(x = number_of_reviews, fill = host_is_superhost)) +
  geom_histogram(binwidth = 10)

Ejercicio 16

Analizar mediante un modelo de regresión binomial si las variables number_of_reviews, reviews_per_month y price influyen en ser un superhost. Reflexiona sobre las siguientes afirmaciones: 1) El modelo permite informar a un anfitrión sobre qué debe hacer para convertirse en un superhost; 2) El modelo permite saber qué debe evitar un anfitrión que tenga la aspiración de convertirse en superhost. Por último, reflexiona sobre lo siguiente: ¿es el precio el que influye en ser un superhost, o es el hecho de ser un superhost el que puede influir en el precio?

## 
## Call:
## glm(formula = host_is_superhost ~ number_of_reviews + reviews_per_month + 
##     price, family = "binomial", data = airbnb)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.6679  -0.6975  -0.5793  -0.4964   2.0939  
## 
## Coefficients:
##                     Estimate Std. Error z value Pr(>|z|)    
## (Intercept)       -2.2245786  0.1042547 -21.338  < 2e-16 ***
## number_of_reviews  0.0061356  0.0012294   4.991 6.01e-07 ***
## reviews_per_month  0.2697030  0.0271343   9.940  < 2e-16 ***
## price              0.0018653  0.0004753   3.924 8.70e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 3481.9  on 3189  degrees of freedom
## Residual deviance: 3225.9  on 3186  degrees of freedom
##   (628 observations deleted due to missingness)
## AIC: 3233.9
## 
## Number of Fisher Scoring iterations: 4
##              Predicted FALSE Predicted TRUE Total
## Actual FALSE            2344             95  2439
## Actual TRUE              681             70   751
## Total                   3025            165  3190

Ejercicio 17

Vamos a considerar más variables y, a través de una stepwise regression, conocer el subconjunto de variables significativas. Incluye las variables host_response_time, host_response_rate, is_location_exact, room_type, bathrooms, bedrooms, beds, bed_type, price, minimum_nights, availability_30, availability_60, availability_90, availability_365, number_of_reviews, review_scores_rating, review_scores_accuracy, review_scores_cleanliness, review_scores_checkin, review_scores_communication, review_scores_location, review_scores_value, cancellation_policy, reviews_per_month, tv, internet, free_parking, air_conditioning, heating, pets_allowed, breakfast, smoke_detector, kitchen, washer, dryer. ¿Cuál es el porcentaje de acierto del modelo? ¿Qué variables nos hacen aumentar nuestra probabilidad de ser superhost, o cuáles nos restan posibilidades?

## 
## Call:
## glm(formula = host_is_superhost ~ ., family = "binomial", data = airbnb_2)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.8207  -0.7550  -0.3762   0.5097   4.6228  
## 
## Coefficients:
##                                        Estimate Std. Error z value Pr(>|z|)    
## (Intercept)                          -4.224e+01  3.505e+00 -12.051  < 2e-16 ***
## host_response_timewithin a day       -7.564e-01  1.184e+00  -0.639 0.522798    
## host_response_timewithin a few hours -3.256e-01  1.197e+00  -0.272 0.785589    
## host_response_timewithin an hour     -2.926e-01  1.204e+00  -0.243 0.807985    
## host_response_rate                    2.832e+00  8.548e-01   3.313 0.000924 ***
## is_location_exactTRUE                 1.513e-01  1.870e-01   0.809 0.418476    
## room_typePrivate room                 1.320e-01  1.349e-01   0.978 0.327990    
## room_typeShared room                 -2.924e-01  4.600e-01  -0.636 0.525034    
## bathrooms                            -2.662e-02  1.160e-01  -0.229 0.818501    
## bedrooms                             -2.339e-02  1.032e-01  -0.227 0.820595    
## beds                                 -1.191e-01  7.320e-02  -1.627 0.103687    
## bed_typeCouch                         6.028e-01  1.469e+00   0.410 0.681536    
## bed_typeFuton                         6.536e-01  9.179e-01   0.712 0.476423    
## bed_typePull-out Sofa                -6.479e-03  9.735e-01  -0.007 0.994689    
## bed_typeReal Bed                      3.328e-01  8.399e-01   0.396 0.691925    
## price                                 2.683e-03  8.208e-04   3.269 0.001078 ** 
## minimum_nights                        1.290e-03  3.544e-03   0.364 0.715889    
## availability_30                      -1.600e-03  1.248e-02  -0.128 0.897973    
## availability_60                      -4.799e-03  1.346e-02  -0.356 0.721481    
## availability_90                       5.977e-03  7.149e-03   0.836 0.403138    
## availability_365                     -9.293e-04  4.904e-04  -1.895 0.058107 .  
## number_of_reviews                     8.893e-03  1.516e-03   5.866 4.46e-09 ***
## review_scores_rating                  1.420e-01  2.355e-02   6.032 1.62e-09 ***
## review_scores_accuracy                4.330e-01  1.560e-01   2.777 0.005493 ** 
## review_scores_cleanliness             5.627e-01  1.435e-01   3.920 8.84e-05 ***
## review_scores_checkin                 3.019e-01  2.336e-01   1.292 0.196319    
## review_scores_communication           7.057e-01  2.713e-01   2.601 0.009301 ** 
## review_scores_location                5.283e-02  1.099e-01   0.481 0.630643    
## review_scores_value                   2.584e-01  1.233e-01   2.095 0.036186 *  
## cancellation_policymoderate           4.532e-01  1.401e-01   3.234 0.001221 ** 
## cancellation_policystrict             6.998e-01  1.452e-01   4.821 1.43e-06 ***
## reviews_per_month                     1.694e-01  3.329e-02   5.087 3.63e-07 ***
## tvTRUE                                7.387e-02  1.256e-01   0.588 0.556526    
## internetTRUE                          7.340e-01  5.263e-01   1.395 0.163157    
## free_parkingTRUE                     -3.584e-02  1.071e-01  -0.335 0.737893    
## air_conditioningTRUE                 -1.407e-01  1.298e-01  -1.084 0.278584    
## heatingTRUE                          -1.815e-01  3.114e-01  -0.583 0.559901    
## pets_allowedTRUE                      2.027e-01  1.087e-01   1.864 0.062372 .  
## breakfastTRUE                         4.961e-03  1.811e-01   0.027 0.978151    
## smoke_detectorTRUE                    4.579e-01  1.913e-01   2.394 0.016675 *  
## kitchenTRUE                          -2.786e-01  1.784e-01  -1.562 0.118328    
## washerTRUE                            2.682e-01  2.344e-01   1.144 0.252452    
## dryerTRUE                            -3.327e-01  2.512e-01  -1.324 0.185464    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 3210.2  on 2833  degrees of freedom
## Residual deviance: 2492.6  on 2791  degrees of freedom
## AIC: 2578.6
## 
## Number of Fisher Scoring iterations: 6
## 
## Call:
## glm(formula = host_is_superhost ~ host_response_time + host_response_rate + 
##     beds + price + number_of_reviews + review_scores_rating + 
##     review_scores_accuracy + review_scores_cleanliness + review_scores_communication + 
##     review_scores_value + cancellation_policy + reviews_per_month + 
##     internet + pets_allowed + smoke_detector + kitchen, family = "binomial", 
##     data = airbnb_2)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.8990  -0.7560  -0.3862   0.5113   4.6671  
## 
## Coefficients:
##                                        Estimate Std. Error z value Pr(>|z|)    
## (Intercept)                          -4.045e+01  3.140e+00 -12.880  < 2e-16 ***
## host_response_timewithin a day       -7.978e-01  1.183e+00  -0.674 0.500064    
## host_response_timewithin a few hours -3.623e-01  1.195e+00  -0.303 0.761839    
## host_response_timewithin an hour     -3.471e-01  1.203e+00  -0.289 0.772863    
## host_response_rate                    2.988e+00  8.507e-01   3.512 0.000444 ***
## beds                                 -1.501e-01  5.620e-02  -2.670 0.007574 ** 
## price                                 2.482e-03  6.974e-04   3.559 0.000372 ***
## number_of_reviews                     8.662e-03  1.474e-03   5.875 4.22e-09 ***
## review_scores_rating                  1.465e-01  2.280e-02   6.425 1.32e-10 ***
## review_scores_accuracy                4.541e-01  1.545e-01   2.940 0.003284 ** 
## review_scores_cleanliness             5.685e-01  1.410e-01   4.033 5.51e-05 ***
## review_scores_communication           8.142e-01  2.560e-01   3.180 0.001471 ** 
## review_scores_value                   2.690e-01  1.205e-01   2.232 0.025637 *  
## cancellation_policymoderate           4.503e-01  1.379e-01   3.265 0.001095 ** 
## cancellation_policystrict             6.757e-01  1.421e-01   4.755 1.99e-06 ***
## reviews_per_month                     1.748e-01  3.224e-02   5.424 5.83e-08 ***
## internetTRUE                          7.495e-01  5.126e-01   1.462 0.143651    
## pets_allowedTRUE                      2.031e-01  1.061e-01   1.914 0.055679 .  
## smoke_detectorTRUE                    4.416e-01  1.874e-01   2.356 0.018472 *  
## kitchenTRUE                          -3.277e-01  1.640e-01  -1.999 0.045660 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 3210.2  on 2833  degrees of freedom
## Residual deviance: 2505.5  on 2814  degrees of freedom
## AIC: 2545.5
## 
## Number of Fisher Scoring iterations: 6
##              Predicted FALSE Predicted TRUE Total
## Actual FALSE            1986            129  2115
## Actual TRUE              467            252   719
## Total                   2453            381  2834

Ejercicio 18

Obtén las frecuencias de barrios (neighbourhood_group_cleansed).

## 
##             Ballard         Beacon Hill        Capitol Hill             Cascade 
##                 230                 118                 567                  89 
##        Central Area            Delridge            Downtown            Interbay 
##                 369                  79                 530                  11 
##           Lake City            Magnolia           Northgate Other neighborhoods 
##                  67                  61                  80                 794 
##          Queen Anne      Rainier Valley         Seward Park University District 
##                 295                 159                  44                 122 
##        West Seattle 
##                 203

Ejercicio 19

Obtén las frecuencias del número de alojamientos de los anfitriones (host_total_listings_count). Según aparece en la propia web de AirBnB, “Some Airbnb hosts have multiple listings. A host may list separate rooms in the same apartment, or multiple apartments or homes available in their entirity.”.

## 
##    1    2    3    4    5    6    7    8    9   10   11   12   13   15   17   18 
## 2179  620  261  151   98   48   30   23   28   26   22   12   12    3   16   19 
##   19   21   34   36   37   48   84  163  169  354  502 
##    4   21   67   36   37   46    2    4   39   10    2

Ejercicio 20

Obtener un histograma con los tipos de alojamientos (room_type).

Ejercicio 21

Obtener un box_plot que informe de los precios según el tipo de alojamiento. Representar también el histograma de frecuencias de los precios para cada tipo de alojamiento.

Ejercicio 22

Analiza cuántos anfitriones ofrecen descuentos semanales o mensuales.

##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##    20.0    75.0   100.0   127.7   150.0   999.0       1
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   100.0   413.5   550.0   567.6   700.0   999.0    2284
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   500.0   750.0   850.0   825.7   900.0   995.0    3697

Ejercicio 23

¿Qué descuento promedio se obtiene por reservas semanales? ¿Hay descuentos negativos?

##    descuento       
##  Min.   :-0.81356  
##  1st Qu.: 0.02597  
##  Median : 0.10204  
##  Mean   : 0.09245  
##  3rd Qu.: 0.17184  
##  Max.   : 0.62585

Ejercicio 24

Vamos a realizar un análisis de componentes principales, con la ayuda de la librería factoextra y la función prcomp, sobre las variables relacionadas con las puntuaciones de las evaluaciones (review_scores_rating, review_scores_accuracy, review_scores_cleanliness, review_scores_checkin, review_scores_communication, review_scores_location, review_scores_value). Comenta los resultados.

airbnb %>%
  dplyr::select(review_scores_rating, review_scores_accuracy, review_scores_cleanliness,
         review_scores_checkin, review_scores_communication, review_scores_location,
         review_scores_value) %>%
  na.exclude() %>%
  cor()
##                             review_scores_rating review_scores_accuracy
## review_scores_rating                   1.0000000              0.6224384
## review_scores_accuracy                 0.6224384              1.0000000
## review_scores_cleanliness              0.6423803              0.5442170
## review_scores_checkin                  0.5219136              0.4072049
## review_scores_communication            0.5436263              0.4237865
## review_scores_location                 0.3687138              0.2682418
## review_scores_value                    0.6962878              0.5639585
##                             review_scores_cleanliness review_scores_checkin
## review_scores_rating                        0.6423803             0.5219136
## review_scores_accuracy                      0.5442170             0.4072049
## review_scores_cleanliness                   1.0000000             0.3986247
## review_scores_checkin                       0.3986247             1.0000000
## review_scores_communication                 0.3883384             0.6963219
## review_scores_location                      0.2784285             0.2413970
## review_scores_value                         0.5242362             0.4032225
##                             review_scores_communication review_scores_location
## review_scores_rating                          0.5436263              0.3687138
## review_scores_accuracy                        0.4237865              0.2682418
## review_scores_cleanliness                     0.3883384              0.2784285
## review_scores_checkin                         0.6963219              0.2413970
## review_scores_communication                   1.0000000              0.2850327
## review_scores_location                        0.2850327              1.0000000
## review_scores_value                           0.4641708              0.3696994
##                             review_scores_value
## review_scores_rating                  0.6962878
## review_scores_accuracy                0.5639585
## review_scores_cleanliness             0.5242362
## review_scores_checkin                 0.4032225
## review_scores_communication           0.4641708
## review_scores_location                0.3696994
## review_scores_value                   1.0000000
library(factoextra)
res_pca <- airbnb %>%
  dplyr::select(review_scores_rating, review_scores_accuracy, review_scores_cleanliness,
         review_scores_checkin, review_scores_communication, review_scores_location,
         review_scores_value) %>%
  na.exclude() %>%
  prcomp(scale = TRUE)
fviz_eig(res_pca)

fviz_pca_var(res_pca,
             col.ind = "contrib",
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE)

Ejercicio 25

Hasta aquí los ejercicios propuestos en el tema. Pero si se te ocurre cualquier otro análisis interesante, bienvenido sea.

3 Resumen de funciones empleadas en el capítulo

  • as.Date

  • as.factor

  • as.logical

  • as.numeric

  • cor

  • fviz_eig

  • fviz_pca_var

  • geom_bar

  • geom_boxplot

  • geom_density_2d_filled

  • geom_density_2d

  • geom_histogram

  • geom_point

  • ggplot

  • glm

  • group_by

  • hist

  • length

  • mutate

  • na.exclude

  • ncol

  • nrow

  • plot

  • prcomp

  • select

  • str_replace_all

  • summarise

  • table

  • toupper

  • unique

  • year