TRABAJO PRACTICO N°5

CIENCIA DE DATOS PARA CIUDADES II: Analizando recorridos y distancias en la Ciudad de BOSTON, MASSACHUSETTS

Snyders, Federico / Vargas, Juan

library(tidyverse)
## -- Attaching packages ----------------------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.0     v purrr   0.3.3
## v tibble  2.1.3     v dplyr   0.8.5
## v tidyr   1.0.2     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.5.0
## -- Conflicts -------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(sf)
## Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(ggmap)
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
library(osrm)
## Data: (c) OpenStreetMap contributors, ODbL 1.0 - http://www.openstreetmap.org/copyright
## Routing: OSRM - http://project-osrm.org/
library(leaflet)

#Descargamos el shp de la ciudad de Boston con sus barrios, al igual que el archivo que contiene las comisarias. Fuente: https://data.boston.gov

BOSTON <- st_read("Boston_Neighborhoods.shp")%>%
  st_transform(crs=4326)
## Reading layer `Boston_Neighborhoods' from data source `C:\Users\usuario\Documents\JUAN\POSGRADOS\MAESTRIA EN ECONOMIA URBANA\2020\CIENCIA DE DATOS PARA CIUDADES II\CLASE 5\TP5\TP_5\Boston_Neighborhoods.shp' using driver `ESRI Shapefile'
## Simple feature collection with 26 features and 7 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: 739715.3 ymin: 2908294 xmax: 812255.1 ymax: 2970086
## proj4string:    +proj=lcc +lat_1=42.68333333333333 +lat_2=41.71666666666667 +lat_0=41 +lon_0=-71.5 +x_0=200000.0001016002 +y_0=750000.0000000001 +datum=NAD83 +units=us-ft +no_defs
names(BOSTON)
## [1] "OBJECTID"   "Name"       "Acres"      "Neighborho" "SqMiles"   
## [6] "ShapeSTAre" "ShapeSTLen" "geometry"
BOSTON_POLICIAS <- st_read("Boston_Police_Stations.shp")%>%
  st_transform(crs=4326)
## Reading layer `Boston_Police_Stations' from data source `C:\Users\usuario\Documents\JUAN\POSGRADOS\MAESTRIA EN ECONOMIA URBANA\2020\CIENCIA DE DATOS PARA CIUDADES II\CLASE 5\TP5\TP_5\Boston_Police_Stations.shp' using driver `ESRI Shapefile'
## Simple feature collection with 13 features and 13 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: 750621.8 ymin: 2918710 xmax: 780828 ymax: 2962523
## proj4string:    +proj=lcc +lat_1=42.68333333333333 +lat_2=41.71666666666667 +lat_0=41 +lon_0=-71.5 +x_0=200000.0001016002 +y_0=750000.0000000001 +datum=NAD83 +units=us-ft +no_defs
names(BOSTON_POLICIAS)
##  [1] "OBJECTID"   "BLDG_ID"    "BID"        "ADDRESS"    "POINT_X"   
##  [6] "POINT_Y"    "NAME"       "NEIGHBORHO" "CITY"       "ZIP"       
## [11] "FT_SQFT"    "STORY_HT"   "PARCEL_ID"  "geometry"

#Buscamos el centroide de cada barrio de la ciudad y lo mostramos en un mapa

BOSTON_centroides <- BOSTON %>%
  st_centroid()
## Warning in st_centroid.sf(.): st_centroid assumes attributes are constant over
## geometries of x
## Warning in st_centroid.sfc(st_geometry(x), of_largest_polygon =
## of_largest_polygon): st_centroid does not give correct centroids for longitude/
## latitude data
ggplot()+
  geom_sf(data=BOSTON, fill="light gray", alpha= .5 )+
  geom_sf(data=BOSTON_centroides , size=2, color = "red")+
  geom_sf_text(data=BOSTON, aes(label = Name), size=2, colour = "black")+
  labs(title = "BARRIOS DE BOSTON",
         subtitle = "Centro geometrico de cada barrio",
         fill="Barrios",
         caption= "Fuente: https://data.boston.gov/dataset")+
  theme_void()
## Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may not
## give correct results for longitude/latitude data

#Seleccionamos como barrio centrico South Boston y el barrio Hyde Park como barrio periferico.

BOSTON_centroides <- BOSTON_centroides %>%
  filter(Name=="Hyde Park" | Name =="South Boston")%>%
  mutate(ubicacion=if_else(Name=="South Boston", "CENTRO", "PERIFERIA"))
BOSTON_centroides <- cbind(BOSTON_centroides, st_coordinates(BOSTON_centroides)) %>%
                      st_set_geometry(NULL)
BOSTON_POLICIAS <- cbind(BOSTON_POLICIAS, st_coordinates(BOSTON_POLICIAS)) %>%
                      st_set_geometry(NULL)

#En el siguiente mapa se muestran los centroides del barrio periferico y central, al igual que la ubicacion de cada comisaria.

ggplot()+
  geom_sf(data=BOSTON, fill="light blue", alpha= .5 )+
  geom_point(data= BOSTON_POLICIAS, aes(x=X, y=Y), color= "blue", size=3)+
    geom_point(data=BOSTON_centroides, aes(x=X, y=Y, color=ubicacion), size=5)+
  labs(title = "BARRIOS y SERVICOS DE BOSTON",
         subtitle = "Centro geometrico de cada barrio",
         color="Ubicacion",
         caption= "Fuente:https://data.boston.gov/dataset")+
  theme_void()

RUTEO

#Realizamos el ruteo para las comisarias desde el barrio central South Boston

ruteo_a_COMISARIAS <- function(o_nombre, o_x, o_y, d_nombre, d_x, d_y) {
  
  ruta <- osrmRoute(src = c(o_nombre, o_x, o_y),
                    dst = c(d_nombre, d_x, d_y), 
                    returnclass = "sf",
                    overview = "full")
  
  cbind(ORIGEN = o_nombre, DESTINO = d_nombre, ruta)
  
}
COMISARIAS_SouthBoston <- BOSTON_POLICIAS %>% 
  mutate(ORIGEN="South Boston") %>% 
  left_join(BOSTON_centroides, by=c("ORIGEN"="Name")) %>% 
   rename(NOMBRE_ORIGEN=ORIGEN,
         LON_ORIGEN= X.y,
         LAT_ORIGEN= Y.y,
         NOMBRE_DESTINO= NAME,
         LON_DESTINO= X.x,
         LAT_DESTINO= Y.x)%>% 
   select(NOMBRE_ORIGEN, LON_ORIGEN, LAT_ORIGEN, NOMBRE_DESTINO, LON_DESTINO, LAT_DESTINO)
## Warning: Column `ORIGEN`/`Name` joining character vector and factor, coercing
## into character vector
ruteo_POLICIAS_SouthBoston <- list(COMISARIAS_SouthBoston$NOMBRE_ORIGEN, COMISARIAS_SouthBoston$LON_ORIGEN,COMISARIAS_SouthBoston$LAT_ORIGEN,
                   COMISARIAS_SouthBoston$NOMBRE_DESTINO, COMISARIAS_SouthBoston$LON_DESTINO,COMISARIAS_SouthBoston$LAT_DESTINO)

ruteo_centrico <- pmap(ruteo_POLICIAS_SouthBoston, ruteo_a_COMISARIAS) %>% 
  reduce(rbind)
ruteo_centrico <-mutate(ruteo_centrico, RUTA = paste(ORIGEN,"a", DESTINO))
arrange(ruteo_centrico,distance)
## Simple feature collection with 13 features and 7 fields
## geometry type:  LINESTRING
## dimension:      XY
## bbox:           xmin: -71.151 ymin: 42.2526 xmax: -71.03647 ymax: 42.38412
## CRS:            EPSG:4326
## First 10 features:
##          ORIGEN                      DESTINO          src dst  duration
## 1  South Boston  District C-6 Police Station South Boston   8  3.433333
## 2  South Boston  District D-4 Police Station South Boston  10  7.188333
## 3  South Boston   Boston Police Headquarters South Boston   1 10.508333
## 4  South Boston  District B-2 Police Station South Boston   5 11.580000
## 5  South Boston  District A-1 Police Station South Boston   2 11.918333
## 6  South Boston District C-11 Police Station South Boston   7 12.918333
## 7  South Boston District E-13 Police Station South Boston  11 16.841667
## 8  South Boston  District B-3 Police Station South Boston   6 16.443333
## 9  South Boston  District A-7 Police Station South Boston   4 14.738333
## 10 South Boston District A-15 Police Station South Boston   3 15.550000
##    distance                                        RUTA
## 1    1.2157  South Boston a District C-6 Police Station
## 2    2.6794  South Boston a District D-4 Police Station
## 3    4.3258   South Boston a Boston Police Headquarters
## 4    4.9952  South Boston a District B-2 Police Station
## 5    5.1802  South Boston a District A-1 Police Station
## 6    6.3539 South Boston a District C-11 Police Station
## 7    7.1249 South Boston a District E-13 Police Station
## 8    7.3018  South Boston a District B-3 Police Station
## 9    7.6408  South Boston a District A-7 Police Station
## 10   9.2201 South Boston a District A-15 Police Station
##                          geometry
## 1  LINESTRING (-71.04465 42.33...
## 2  LINESTRING (-71.04465 42.33...
## 3  LINESTRING (-71.04465 42.33...
## 4  LINESTRING (-71.04465 42.33...
## 5  LINESTRING (-71.04465 42.33...
## 6  LINESTRING (-71.04465 42.33...
## 7  LINESTRING (-71.04465 42.33...
## 8  LINESTRING (-71.04465 42.33...
## 9  LINESTRING (-71.04465 42.33...
## 10 LINESTRING (-71.04465 42.33...

#Observamos que el la comisaria mas cercana se encuentra a 1.21 km con un tiempo de viajeen condiciones normales es de 3.43 minutos y la mas alejada esta a 9.22 km con un tiempo en condiciones normales es de viaje de 15.55.

#El siguiente mapa muestra las rutas desde el barrio centrio con destino a las comisarias.

leaflet(ruteo_centrico) %>%
  addTiles() %>%
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  addPolylines(color = ~colorNumeric("plasma", ruteo_centrico$distance)(distance),
              label = ruteo_centrico$RUTA %>%
              lapply(htmltools::HTML)) %>%
  addLegend("bottomright", pal = colorNumeric("plasma", ruteo_centrico$distance), values = ~distance,
            title = "Distancia",
            opacity = 0.6)
COMISARIAS_HydePark <- BOSTON_POLICIAS %>%
  mutate(ORIGEN="Hyde Park") %>%
  left_join(BOSTON_centroides, by=c("ORIGEN"="Name"))%>%
   rename(NOMBRE_ORIGEN=ORIGEN,
         LON_ORIGEN=X.y,
         LAT_ORIGEN=Y.y,
         NOMBRE_DESTINO=NAME,
         LON_DESTINO=X.x,
         LAT_DESTINO=Y.x) %>%
  select(NOMBRE_ORIGEN, LON_ORIGEN, LAT_ORIGEN, NOMBRE_DESTINO, LON_DESTINO, LAT_DESTINO)
## Warning: Column `ORIGEN`/`Name` joining character vector and factor, coercing
## into character vector

#Realizamos el ruteo para las comisarias desde el barrio periferico Hyde Park

ruteo_POLICIAS_HydePark <- list(COMISARIAS_HydePark$NOMBRE_ORIGEN, COMISARIAS_HydePark$LON_ORIGEN,COMISARIAS_HydePark$LAT_ORIGEN,
                   COMISARIAS_HydePark$NOMBRE_DESTINO, COMISARIAS_HydePark$LON_DESTINO,COMISARIAS_HydePark$LAT_DESTINO)

ruteo_periferico <- pmap(ruteo_POLICIAS_HydePark, ruteo_a_COMISARIAS) %>% 
  reduce(rbind)
ruteo_periferico <-mutate(ruteo_periferico, RUTA = paste(ORIGEN,"a", DESTINO))
arrange(ruteo_periferico, distance)
## Simple feature collection with 13 features and 7 fields
## geometry type:  LINESTRING
## dimension:      XY
## bbox:           xmin: -71.15529 ymin: 42.25254 xmax: -71.03647 ymax: 42.38412
## CRS:            EPSG:4326
## First 10 features:
##       ORIGEN                      DESTINO       src dst  duration distance
## 1  Hyde Park District E-18 Police Station Hyde Park  12  1.641667   0.3707
## 2  Hyde Park  District E-5 Police Station Hyde Park  13  8.095000   5.4754
## 3  Hyde Park  District B-3 Police Station Hyde Park   6 11.998333   5.9259
## 4  Hyde Park District E-13 Police Station Hyde Park  11 13.725000   6.6145
## 5  Hyde Park District C-11 Police Station Hyde Park   7 18.586667   8.8677
## 6  Hyde Park  District B-2 Police Station Hyde Park   5 19.743333   9.2533
## 7  Hyde Park   Boston Police Headquarters Hyde Park   1 21.893333   9.9374
## 8  Hyde Park District D-14 Police Station Hyde Park   9 22.693333  13.8882
## 9  Hyde Park  District C-6 Police Station Hyde Park   8 24.763333  18.5258
## 10 Hyde Park  District D-4 Police Station Hyde Park  10 24.498333  18.6604
##                                        RUTA                       geometry
## 1  Hyde Park a District E-18 Police Station LINESTRING (-71.12672 42.25...
## 2   Hyde Park a District E-5 Police Station LINESTRING (-71.12672 42.25...
## 3   Hyde Park a District B-3 Police Station LINESTRING (-71.12672 42.25...
## 4  Hyde Park a District E-13 Police Station LINESTRING (-71.12672 42.25...
## 5  Hyde Park a District C-11 Police Station LINESTRING (-71.12672 42.25...
## 6   Hyde Park a District B-2 Police Station LINESTRING (-71.12672 42.25...
## 7    Hyde Park a Boston Police Headquarters LINESTRING (-71.12672 42.25...
## 8  Hyde Park a District D-14 Police Station LINESTRING (-71.12672 42.25...
## 9   Hyde Park a District C-6 Police Station LINESTRING (-71.12672 42.25...
## 10  Hyde Park a District D-4 Police Station LINESTRING (-71.12672 42.25...

#Apreciamos que la distancia minima a una comisaria es de 370 mts y el tiempo de viaje en condiciones normales es de 1.64 minutos, mientras que la mas distante esta a 18.66 km con un tiempo de viaje en condiciones normales de 24.49 minutos

#El siguiente mapa muestra las rutas a las comisarias desde el barrio periferico.

leaflet(ruteo_periferico) %>%
  addTiles() %>%
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  addPolylines(color = ~colorNumeric("plasma", ruteo_periferico$distance)(distance),
              label = ruteo_periferico$RUTA %>%
              lapply(htmltools::HTML)) %>%
  addLegend("bottomright", pal = colorNumeric("plasma", ruteo_periferico$distance), values = ~distance,
            title = "Distancia",
            opacity = 0.6)