Datos sobre los Airbnb’s de la ciudad de Valencia

CSV
AIRBNB
VALENCIA
Autor/a
Afiliación

Universitat de València

Fecha de publicación

10 de mayo de 2024

Input

En los últimos años, las plataformas de alquiler de alojamientos turísticos como Airbnb, han causado un impacto enorme en las comunidades locales alrededor del mundo, provocando debates sobre cómo afecta a nivel social, económico y urbanístico.

Inside Airbnb, un proyecto impulsado por una misión, se ha convertido en una fuente invaluable de datos y análisis para comprender el impacto de Airbnb en las distintas ciudades. A través de su plataforma en línea, proporcionan acceso a diferentes conjuntos de datos que contienen información detallada sobre los listados de alojamientos en ciudades de todo el mundo, incluida la ciudad de Valencia.

El conjunto de datos listings.csv , sobre el cual vamos a trabajar, se ha descargado de Inside Airbnb. Este ofrece una visión detallada y métricas de los listados de alojamientos en la ciudad de Valencia. Este conjunto de datos contiene una variedad de atributos, como características del alojamiento (número de habitaciones, camas, baños, etc.), ubicación geográfica, calificaciones de los huéspedes y más. Estos datos permiten realizar un análisis exhaustivo del mercado de alquileres turísticos en Valencia y comprender mejor su impacto pero, ¿tenemos los datos listos para tratarlos?

A continuación mostramos otra información de interés:

  • Fecha de cración: 22/06/2023

  • Fecha de revisión: 18/12/2023

Descripción

La base de datos tiene una columna llamada name, la cual contiene cinco tipos de información. Desde las valoraciones de los residentes al número de habitaciones que dispone el alojamiento, así como el tipo de alojamiento. Por lo que habría que separar estos datos en cinco columnas distintas. Además la base de datos dispone de diferentes NA’s que ya iremos viendo si son relevantes o no para el análisis de datos.

Finalmente, para hacer un análisis más centrado en la zona urbana de la capital de la Comunitat Valenciana, vamos a eliminar toda la zona perifèrica, descartando del análisis la zona de La Albufera, Burjassot, Alboraya y alrededores.

Primero cargamos las librerias que nos van a hacer falta para el tratamiento de los datos:

Los datos iniciales de los que disponemos son los siguientes:

listings_inicial <- read_csv("data/listings.csv")
kable(head(listings_inicial))
id name host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm license
48154 Rental unit in Valencia · ★4.59 · 2 bedrooms · 2 beds · 1 bath 219476 Antonio LA SAIDIA MORVEDRE 39.48375 -0.37502 Entire home/apt 80 3 146 2023-12-04 0.91 4 69 18 VT-41540-V
100347 Rental unit in València · ★4.58 · 3 bedrooms · 3 beds · 2 baths 1451371 Santiago EXTRAMURS ARRANCAPINS 39.45965 -0.38453 Entire home/apt NA 3 142 2023-09-01 1.94 1 0 7 NA
136378 Condo in Valencia · ★4.46 · 1 bedroom · 2 beds · 1 bath 591197 Elisa CIUTAT VELLA EL MERCAT 39.47358 -0.37815 Entire home/apt 75 28 25 2023-06-30 0.17 3 0 2 VT-42161-V
149715 Home in Valencia · ★4.64 · 5 bedrooms · 7 beds · 3.5 baths 5947 Susana Barbara POBLATS MARITIMS CABANYAL-CANYAMELAR 39.46746 -0.32813 Entire home/apt 216 2 241 2023-12-10 1.59 1 0 35 Nº TURISMO VT36469V CATEGORIA: standard
152369 Loft in Valencia · ★4.84 · Studio · 1 bed · 1 bath 644376 Oscar CIUTAT VELLA EL CARME 39.47863 -0.38219 Entire home/apt NA 2 80 2019-09-07 0.58 4 0 0 NA
153375 Rental unit in Valencia · 1 bedroom · 2 beds · 1 bath 737412 Florence QUATRE CARRERES MONT-OLIVET 39.46062 -0.36050 Entire home/apt 25 180 0 NA NA 1 269 0 NA
dim(listings_inicial)
[1] 8810   18

Tratamiento

Para solucionar el problema de exceso de datos en una misma columna, vamos a crear nuevas columnas con valores NA, donde iremos añadiendo los datos que saquemos de name.

nuevas_columnas <- data.frame(
  tipo_propiedad = NA,
  calificacion = NA,
  bedrooms = NA,
  beds = NA,
  bath = NA
)

Seguidamente iteraremos sobre cada fila del dataframe, dividiendo el texto en cada punto (·) y eliminando posibles elementos vacíos. Además asignaremos los valores a las nuevas columnas de derecha a izquierda.

for (i in 1:nrow(listings_inicial)) {
  name <- str_trim(listings_inicial$name[i])
  partes <- unlist(str_split(name, "·"))
  partes <- partes[!partes == ""] 
 
  for (j in 1:length(partes)) {
    parte <- trimws(partes[j])
    if (grepl("★", parte)) {
      nuevas_columnas[i, "calificacion"] <- parte
    } else if (grepl("bedrooms?", parte)) {
      nuevas_columnas[i, "bedrooms"] <- parte
    } else if (grepl("beds?", parte)) {
      nuevas_columnas[i, "beds"] <- parte
    } else if (grepl("baths?", parte)) {
      nuevas_columnas[i, "bath"] <- parte
    } else {
      nuevas_columnas[i, "tipo_propiedad"] <- paste(nuevas_columnas[i, "tipo_propiedad"], parte, sep = " ")
    }
  }
}

Estas nuevas columnas quedarán así:

kable(head(nuevas_columnas))
tipo_propiedad calificacion bedrooms beds bath
NA Rental unit in Valencia ★4.59 2 bedrooms 2 beds 1 bath
NA Rental unit in València ★4.58 3 bedrooms 3 beds 2 baths
NA Condo in Valencia ★4.46 1 bedroom 2 beds 1 bath
NA Home in Valencia ★4.64 5 bedrooms 7 beds 3.5 baths
NA Loft in Valencia Studio ★4.84 NA 1 bed 1 bath
NA Rental unit in Valencia NA 1 bedroom 2 beds 1 bath

El dataframe con las nuevas columnas añadidas quedará de la siguiente forma:

listings <- cbind(listings_inicial, nuevas_columnas)
kable(head(listings))
id name host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm license tipo_propiedad calificacion bedrooms beds bath
48154 Rental unit in Valencia · ★4.59 · 2 bedrooms · 2 beds · 1 bath 219476 Antonio LA SAIDIA MORVEDRE 39.48375 -0.37502 Entire home/apt 80 3 146 2023-12-04 0.91 4 69 18 VT-41540-V NA Rental unit in Valencia ★4.59 2 bedrooms 2 beds 1 bath
100347 Rental unit in València · ★4.58 · 3 bedrooms · 3 beds · 2 baths 1451371 Santiago EXTRAMURS ARRANCAPINS 39.45965 -0.38453 Entire home/apt NA 3 142 2023-09-01 1.94 1 0 7 NA NA Rental unit in València ★4.58 3 bedrooms 3 beds 2 baths
136378 Condo in Valencia · ★4.46 · 1 bedroom · 2 beds · 1 bath 591197 Elisa CIUTAT VELLA EL MERCAT 39.47358 -0.37815 Entire home/apt 75 28 25 2023-06-30 0.17 3 0 2 VT-42161-V NA Condo in Valencia ★4.46 1 bedroom 2 beds 1 bath
149715 Home in Valencia · ★4.64 · 5 bedrooms · 7 beds · 3.5 baths 5947 Susana Barbara POBLATS MARITIMS CABANYAL-CANYAMELAR 39.46746 -0.32813 Entire home/apt 216 2 241 2023-12-10 1.59 1 0 35 Nº TURISMO VT36469V CATEGORIA: standard NA Home in Valencia ★4.64 5 bedrooms 7 beds 3.5 baths
152369 Loft in Valencia · ★4.84 · Studio · 1 bed · 1 bath 644376 Oscar CIUTAT VELLA EL CARME 39.47863 -0.38219 Entire home/apt NA 2 80 2019-09-07 0.58 4 0 0 NA NA Loft in Valencia Studio ★4.84 NA 1 bed 1 bath
153375 Rental unit in Valencia · 1 bedroom · 2 beds · 1 bath 737412 Florence QUATRE CARRERES MONT-OLIVET 39.46062 -0.36050 Entire home/apt 25 180 0 NA NA 1 269 0 NA NA Rental unit in Valencia NA 1 bedroom 2 beds 1 bath

Como podemos observar en la columna tipo_propiedad, todas las filas empiezan por NA, vamos a solucionar este error:

listings$tipo_propiedad <- gsub("NA ", "", listings$tipo_propiedad)

Además, nos damos cuenta que en la columna bedrooms tenemos NA’s. Observando los datos iniciales nos fijamos que no hay valores nulos en esta columna, si no que todos los NA’s en realidad son estudios. Por lo que vamos a sustituir los valores.

listings$bedrooms[is.na(listings$bedrooms)] <- "Studio"

También tenemos valores nulos en la columna de calificaciones, y muchos de ellos, por no decir la mayoría, son en realidad alojamientos nuevos en la plataforma. Por lo que vamos a reemplazar los valores nulos de todos aquellas filas donde el numero de valoraciones es menor a 3 por Nuevos.

listings$calificacion[listings$number_of_reviews_ltm < 3 & is.na(listings$calificacion)] <- "★New"
columnas_interes <- listings[, c("calificacion", "tipo_propiedad", "bedrooms", "beds", "bath")]

primeras_10_filas <- head(columnas_interes, 10)
ultimas_10_filas <- tail(columnas_interes, 10)

kable(primeras_10_filas)
calificacion tipo_propiedad bedrooms beds bath
★4.59 Rental unit in Valencia 2 bedrooms 2 beds 1 bath
★4.58 Rental unit in València 3 bedrooms 3 beds 2 baths
★4.46 Condo in Valencia 1 bedroom 2 beds 1 bath
★4.64 Home in Valencia 5 bedrooms 7 beds 3.5 baths
★4.84 Loft in Valencia Studio Studio 1 bed 1 bath
★New Rental unit in Valencia 1 bedroom 2 beds 1 bath
★4.87 Rental unit in Valencia 1 bedroom 1 bed 1 bath
★4.89 Rental unit in Valencia 1 bedroom 2 beds 1 bath
★4.40 Rental unit in Valencia 1 bedroom 1 bed 1 bath
★4.43 Rental unit in Valencia 2 bedrooms 5 beds 1 bath
kable(ultimas_10_filas)
calificacion tipo_propiedad bedrooms beds bath
8801 ★New Rental unit in València 3 bedrooms 3 beds 1 bath
8802 ★New Rental unit in València 1 bedroom 1 bed 1 bath
8803 ★New Rental unit in València 2 bedrooms NA 1 bath
8804 ★New Rental unit in Valencia 2 bedrooms 2 beds 1 bath
8805 ★New Home in València 1 bedroom 1 bed 1 bath
8806 ★New Rental unit in València 1 bedroom 1 bed 1 bath
8807 ★New Rental unit in València 1 bedroom NA 1 bath
8808 ★New Rental unit in València 2 bedrooms 2 beds 1 bath
8809 ★New Rental unit in València 1 bedroom 1 bed 1 bath
8810 ★New Rental unit in València 1 bedroom 1 bed 1 bath

Vemos que tenemos NA en las columnas de Bed y Bath, pero es por que no se dispone de esa información. Al ocurrir en muy pocas filas, vamos a eliminarlas:

a <- listings[complete.cases(listings$beds, listings$bath), ]
filas_eliminadas <- nrow(listings) - nrow(a)
cat("Se eliminaron", filas_eliminadas, "filas que contenían NA en las columnas 'beds' o 'bath'.\n")
Se eliminaron 70 filas que contenían NA en las columnas 'beds' o 'bath'.

Eliminamos también la columna de name, ya que esos datos ya los tenemos en otras columnas bien estructuradas y la columna de licencias, ya que contiene muchos valores nulos y no aporta información para el análisis:

listings<- subset(listings, select = -c(name, license))

kable(head(listings))
id host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm tipo_propiedad calificacion bedrooms beds bath
48154 219476 Antonio LA SAIDIA MORVEDRE 39.48375 -0.37502 Entire home/apt 80 3 146 2023-12-04 0.91 4 69 18 Rental unit in Valencia ★4.59 2 bedrooms 2 beds 1 bath
100347 1451371 Santiago EXTRAMURS ARRANCAPINS 39.45965 -0.38453 Entire home/apt NA 3 142 2023-09-01 1.94 1 0 7 Rental unit in València ★4.58 3 bedrooms 3 beds 2 baths
136378 591197 Elisa CIUTAT VELLA EL MERCAT 39.47358 -0.37815 Entire home/apt 75 28 25 2023-06-30 0.17 3 0 2 Condo in Valencia ★4.46 1 bedroom 2 beds 1 bath
149715 5947 Susana Barbara POBLATS MARITIMS CABANYAL-CANYAMELAR 39.46746 -0.32813 Entire home/apt 216 2 241 2023-12-10 1.59 1 0 35 Home in Valencia ★4.64 5 bedrooms 7 beds 3.5 baths
152369 644376 Oscar CIUTAT VELLA EL CARME 39.47863 -0.38219 Entire home/apt NA 2 80 2019-09-07 0.58 4 0 0 Loft in Valencia Studio ★4.84 Studio 1 bed 1 bath
153375 737412 Florence QUATRE CARRERES MONT-OLIVET 39.46062 -0.36050 Entire home/apt 25 180 0 NA NA 1 269 0 Rental unit in Valencia ★New 1 bedroom 2 beds 1 bath

Y para finalizar vamos a crear unas nuevas columnas con los datos numéricos de calificaciones, habitaciones, camas y baños para poder tratarlos y analizarlos correctamente.

listings_procesado <- listings

for (i in 1:nrow(listings)) {
  if (!is.na(listings$calificacion[i])) {
    calificacion <- as.numeric(gsub("[^0-9.]+", "", listings$calificacion[i]))
    if (!is.na(calificacion)) {
      listings_procesado$ncalificación[i] <- calificacion
    }
  }
  

  if (!is.na(listings$bedrooms[i])) {
    bedrooms <- as.numeric(gsub("[^0-9]+", "", listings$bedrooms[i]))
    if (!is.na(bedrooms)) {
      listings_procesado$nbedrooms[i] <- bedrooms
    }
  }

  if (!is.na(listings$beds[i])) {
    beds <- as.numeric(gsub("[^0-9]+", "", listings$beds[i]))
    if (!is.na(beds)) {
      listings_procesado$nbeds[i] <- beds
    }
  }

  if (!is.na(listings$bath[i])) {
    bath <- as.numeric(gsub("[^0-9.]+", "", listings$bath[i]))
    if (!is.na(bath)) {
      listings_procesado$nbath[i] <- bath
    }
  }
}

kable(head(listings_procesado))
id host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm tipo_propiedad calificacion bedrooms beds bath ncalificación nbedrooms nbeds nbath
48154 219476 Antonio LA SAIDIA MORVEDRE 39.48375 -0.37502 Entire home/apt 80 3 146 2023-12-04 0.91 4 69 18 Rental unit in Valencia ★4.59 2 bedrooms 2 beds 1 bath 4.59 2 2 1.0
100347 1451371 Santiago EXTRAMURS ARRANCAPINS 39.45965 -0.38453 Entire home/apt NA 3 142 2023-09-01 1.94 1 0 7 Rental unit in València ★4.58 3 bedrooms 3 beds 2 baths 4.58 3 3 2.0
136378 591197 Elisa CIUTAT VELLA EL MERCAT 39.47358 -0.37815 Entire home/apt 75 28 25 2023-06-30 0.17 3 0 2 Condo in Valencia ★4.46 1 bedroom 2 beds 1 bath 4.46 1 2 1.0
149715 5947 Susana Barbara POBLATS MARITIMS CABANYAL-CANYAMELAR 39.46746 -0.32813 Entire home/apt 216 2 241 2023-12-10 1.59 1 0 35 Home in Valencia ★4.64 5 bedrooms 7 beds 3.5 baths 4.64 5 7 3.5
152369 644376 Oscar CIUTAT VELLA EL CARME 39.47863 -0.38219 Entire home/apt NA 2 80 2019-09-07 0.58 4 0 0 Loft in Valencia Studio ★4.84 Studio 1 bed 1 bath 4.84 2 1 1.0
153375 737412 Florence QUATRE CARRERES MONT-OLIVET 39.46062 -0.36050 Entire home/apt 25 180 0 NA NA 1 269 0 Rental unit in Valencia ★New 1 bedroom 2 beds 1 bath 4.59 1 2 1.0

Renombramos el dataframe

listings<- listings_procesado

Como ya hemos dicho anteriormente, queremos eliminar los datos periféricos de la ciudad, enfocandonos en el centro de la ciudad.

listings_sf <- sf::st_as_sf(listings, coords = c("longitude", "latitude"), crs = 4326)
spain_mun<-  mapSpain::esp_get_munic()
valencia <- mapSpain::esp_get_munic() %>%
  filter(cmun == "250", name == "Valencia")
valencia_tr <- st_transform(valencia, crs = 4326)
airbnb_valencia <- st_intersection(listings_sf, valencia_tr)

leaflet() %>%
  addTiles() %>%
  # Añadir capa para el contorno de Valencia
  addPolygons(data = valencia_tr, fillColor = "lightblue", fillOpacity = 0.5) %>%
  # Añadir capa para los hidrantes dentro de Valencia
  addCircleMarkers(data = airbnb_valencia, color = "red", radius = 0.5)

Vamos a crear el nuevo polígono para seleccionar la zona con la que queremos trabajar. Primero estableceremos las esquinas del polígono para crearlo. Después realizaremos la intersección con el área total de Valencia.

coords_area_central <- matrix(c(
  c(-0.404, 39.504),  # Esquina superior izquierda 
  c(-0.331, 39.481),  # Esquina superior derecha 
  c(-0.345, 39.432),  # Esquina inferior derecha
  c(-0.408, 39.454),  # Esquina inferior izquierda
  c(-0.404, 39.504)   # Volvemos al punto inicial para cerrar el polígono
), ncol = 2, byrow = TRUE)

poligono_area_central <- st_polygon(list(coords_area_central))

area_central_sf <- st_sf(geometry = st_sfc(poligono_area_central))
area_central_sf <- st_set_crs(area_central_sf, 4326)


airbnb_valencia <- st_set_crs(airbnb_valencia, 4326)
airbnb_valencia_central <- st_intersection(airbnb_valencia, area_central_sf)

Output

Los datos finales quedan de la siguiente forma:

id host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm tipo_propiedad calificacion bedrooms beds bath ncalificación nbedrooms nbeds nbath
48154 219476 Antonio LA SAIDIA MORVEDRE 39.48375 -0.37502 Entire home/apt 80 3 146 2023-12-04 0.91 4 69 18 Rental unit in Valencia ★4.59 2 bedrooms 2 beds 1 bath 4.59 2 2 1.0
100347 1451371 Santiago EXTRAMURS ARRANCAPINS 39.45965 -0.38453 Entire home/apt NA 3 142 2023-09-01 1.94 1 0 7 Rental unit in València ★4.58 3 bedrooms 3 beds 2 baths 4.58 3 3 2.0
136378 591197 Elisa CIUTAT VELLA EL MERCAT 39.47358 -0.37815 Entire home/apt 75 28 25 2023-06-30 0.17 3 0 2 Condo in Valencia ★4.46 1 bedroom 2 beds 1 bath 4.46 1 2 1.0
149715 5947 Susana Barbara POBLATS MARITIMS CABANYAL-CANYAMELAR 39.46746 -0.32813 Entire home/apt 216 2 241 2023-12-10 1.59 1 0 35 Home in Valencia ★4.64 5 bedrooms 7 beds 3.5 baths 4.64 5 7 3.5
152369 644376 Oscar CIUTAT VELLA EL CARME 39.47863 -0.38219 Entire home/apt NA 2 80 2019-09-07 0.58 4 0 0 Loft in Valencia Studio ★4.84 Studio 1 bed 1 bath 4.84 2 1 1.0
153375 737412 Florence QUATRE CARRERES MONT-OLIVET 39.46062 -0.36050 Entire home/apt 25 180 0 NA NA 1 269 0 Rental unit in Valencia ★New 1 bedroom 2 beds 1 bath 4.59 1 2 1.0
id host_id host_name neighbourhood_group neighbourhood latitude longitude room_type price minimum_nights number_of_reviews last_review reviews_per_month calculated_host_listings_count availability_365 number_of_reviews_ltm tipo_propiedad calificacion bedrooms beds bath ncalificación nbedrooms nbeds nbath
8805 1.048498e+18 479209522 Rogelio Jose POBLATS DEL SUD EL PALMAR 39.30721 -0.3180654 Entire home/apt 63 1 0 NA NA 4 269 0 Home in València ★New 1 bedroom 1 bed 1 bath 4.59 1 1 1
8806 1.048519e+18 501323625 Roots Capital EXTRAMURS LA ROQUETA 39.46894 -0.3823481 Entire home/apt 96 1 0 NA NA 4 270 0 Rental unit in València ★New 1 bedroom 1 bed 1 bath 4.59 1 1 1
8807 1.048542e+18 551372808 Jesus RASCANYA TORREFIEL 39.49745 -0.3733145 Private room 28 1 0 NA NA 1 269 0 Rental unit in València ★New 1 bedroom NA 1 bath 4.59 1 2 1
8808 1.048595e+18 481770351 Luisa EXTRAMURS LA ROQUETA 39.46559 -0.3791061 Entire home/apt 103 1 0 NA NA 1 177 0 Rental unit in València ★New 2 bedrooms 2 beds 1 bath 4.59 2 2 1
8809 1.048691e+18 232402371 Angie LA SAIDIA MORVEDRE 39.48564 -0.3750928 Private room 24 1 0 NA NA 1 269 0 Rental unit in València ★New 1 bedroom 1 bed 1 bath 4.59 1 1 1
8810 1.048693e+18 379846908 Maria POBLATS MARITIMS LA MALVA-ROSA 39.47729 -0.3323300 Private room 34 1 0 NA NA 2 135 0 Rental unit in València ★New 1 bedroom 1 bed 1 bath 4.59 1 1 1

El fichero generado con este procedimiento se puede obtener de aquí



Proyecto de Innovación Educativa Emergente (PIEE-2737007)