TAREA CLASE I

library(sf)
## Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(tidyverse)
## Registered S3 method overwritten by 'rvest':
##   method            from
##   read_xml.response xml2
## -- Attaching packages -------------------------------------------------------------------------- tidyverse 1.2.1 --
## v ggplot2 3.2.0       v purrr   0.3.2  
## v tibble  2.1.1       v dplyr   0.8.0.1
## v tidyr   0.8.3       v stringr 1.4.0  
## v readr   1.3.1       v forcats 0.4.0
## -- Conflicts ----------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

Voy a trabajar en la CABA, con datos de gimnasios por barrios

barrios <- st_read("http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson")
## Reading layer `barrios_badata' from data source `http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson' using driver `GeoJSON'
## Simple feature collection with 48 features and 4 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -58.53152 ymin: -34.70529 xmax: -58.33515 ymax: -34.52649
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs

ahora traigo los gimnasios

gimnasios <- read.csv("~/MEU/MU115 - CIencia de Datos II/gimnasios.csv", header=TRUE)
names(gimnasios)
##  [1] "long"                    "lat"                    
##  [3] "periodo"                 "razon_social"           
##  [5] "nombre_fantasia"         "clasificacion"          
##  [7] "telefono"                "disposicion_2015_2016"  
##  [9] "disposicion_2017"        "disposicion_2018"       
## [11] "calle"                   "altura"                 
## [13] "piso"                    "barrio"                 
## [15] "comuna"                  "codigo_postal"          
## [17] "codigo_postal_argentino"

Ahora los dibujo los dos juntos, ya que uno es “Espacial”, y el otro es un dataset comun.Lo hago con ggplot

ggplot() +
    geom_sf(data = barrios) +
    geom_point(data = gimnasios, 
               aes(x = long, y = lat),
               alpha = .3, 
               color = "red")
## Warning: Removed 4 rows containing missing values (geom_point).

Ahora limpio la base de datos que no tienen datos cargados en filas, porque sino dara error. eso lo logro con !lis.na… etc, filter es x filas, select es para columnas. Convierto en espacial mi dataset

gimnasios <- gimnasios %>%
  select(-barrio) %>%
    filter(!is.na(lat), !is.na(long)) %>% 
    st_as_sf(coords = c("long", "lat"), crs = 4326)

Entonces, como ahora son dos dataframes espaciales, se dibujan de vuelta con geom_sf

ggplot() +
  geom_sf(data = barrios) +
  geom_sf(data = gimnasios, color = "red", alpha = .3)

Para hacer spatial join y poder unir ambos dataframes espaciales, armo un dataframe nuevo gimnasios_en_barrios

gimnasios_en_barrios <- st_join(gimnasios, barrios)
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
gimnasios_en_barrios %>% head
## Simple feature collection with 6 features and 18 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: -58.50274 ymin: -34.66294 xmax: -58.36394 ymax: -34.56279
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##   periodo             razon_social            nombre_fantasia
## 1  201810 LABOR DEL MOVIMIENTO S.A SPORT CLUB (PUERTO MADERO)
## 2  201810      RICARDO ANGEL VEPPO                LOS ASIRIOS
## 3  201810   FOSQUE GERARDO ERNESTO      FOSQUE FITNESS CENTER
## 4  201810              LIGRAN S.A.         GYM - A MONASTERIO
## 5  201810    MARIA ANGELA ESCRIVA          INSTITUTO POTENCIA
## 6  201810           OXTREAM S.R.L.     GIMNASIO URBAN FITNESS
##   clasificacion  telefono disposicion_2015_2016  disposicion_2017
## 1      GIMNASIO 4315-1411     DI-9832-DGHP-2015                  
## 2      GIMNASIO 4683-6924                       DI-5940-DGHP-2017
## 3      GIMNASIO 2062-3856                       DI-6912-DGHP-2017
## 4      GIMNASIO 4634-1296    DI-10268-DGHP-2015 DI-5534-DGHP-2017
## 5      GIMNASIO 4571-3123     DI-3784-DGHP-2016 DI-5849-DGHP-2017
## 6      GIMNASIO 4896-4136     DI-2765-DGHP-2016       GYM CERRADO
##    disposicion_2018               calle altura piso  comuna.x
## 1 DI-6062-2018-DGHP        JUANA MANSO     295       Comuna 1
## 2 DI-8415-2018-DGHP          EVA PERON    5819       Comuna 9
## 3 DI-8303-2018-DGHP            BRAGADO    5952       Comuna 9
## 4 DI-6114-2018-DGHP        CURAPALIGUE     760       Comuna 7
## 5 DI-7750-2018-DGHP AV. CONSTITUYENTES    4582      Comuna 12
## 6                              MENDOZA    2703      Comuna 13
##   codigo_postal codigo_postal_argentino           barrio comuna.y
## 1          1107                C1107CBE    PUERTO MADERO        1
## 2          1439                C1439BSJ        MATADEROS        9
## 3          1440                C1440ACV        MATADEROS        9
## 4          1406                C1406DAU PARQUE CHACABUCO        7
## 5          1431                C1431EXX VILLA PUEYRREDON       12
## 6          1428                C1428DKU         BELGRANO       13
##   perimetro    area                    geometry
## 1 17725.721 5040971  POINT (-58.36394 -34.6007)
## 2 11124.636 7398179 POINT (-58.48782 -34.66294)
## 3 11124.636 7398179 POINT (-58.50274 -34.65344)
## 4  8406.914 3832117 POINT (-58.44952 -34.63305)
## 5  7522.360 3303240 POINT (-58.49239 -34.58181)
## 6 20609.775 7999240 POINT (-58.46048 -34.56279)

con st set geometry le saco lo geografico/geometrico- Creo un dataframe nuevo que se llama cantidad que une los dos dataframes unidos, y los agrupa por cantidad

cantidad <- gimnasios_en_barrios %>% 
  group_by(barrio) %>% 
  summarise(cantidad = n())%>%
  st_set_geometry(NULL)

hago union entre la tabla cantidad y barrios que es espacial y lo puedo hacer con un leftjoin, y se lo agrego a barrios que ya existia.

barrios_gimnasios <- left_join(barrios, cantidad)
## Joining, by = "barrio"

veo que barrio tiene más gimnasios:

ggplot()+
geom_sf(data=barrios_gimnasios, aes(fill=cantidad))

TAREA CLASE 2

Cargo librerias

library(osmdata)
## Warning: package 'osmdata' was built under R version 3.6.1
## Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
library(tidyverse)
library(leaflet)
## Warning: package 'leaflet' was built under R version 3.6.1
library(sf)
bbox <- getbb("CABA, Buenos Aires")

bbox
##         min       max
## x -58.53146 -58.33512
## y -34.70564 -34.52655
bbox_pol_caba <- getbb("CABA, Buenos Aires", format_out = "sf_polygon")

Le agrego el poligono deBuenos AIres

leaflet() %>%
  addTiles() %>%
  addPolygons(data=bbox_pol_caba)

Descargar Red Vial, le digo de que rectangulo voy a bajar informacion.

Baires <- opq(bbox) %>%
  add_osm_feature(key="highway")

Baires
## $bbox
## [1] "-34.705637,-58.5314588,-34.5265535,-58.3351249"
## 
## $prefix
## [1] "[out:xml][timeout:25];\n(\n"
## 
## $suffix
## [1] ");\n(._;>;);\nout body;"
## 
## $features
## [1] " [\"highway\"]"
## 
## attr(,"class")
## [1] "list"           "overpass_query"

Le cargo las calles, y lo guardo en un dataframe que se llama Baires

Baires <- opq(bbox) %>%
  add_osm_feature(key="highway")%>%
  osmdata_sf
Baires
## Object of class 'osmdata' with:
##                  $bbox : -34.705637,-58.5314588,-34.5265535,-58.3351249
##         $overpass_call : The call submitted to the overpass API
##                  $meta : metadata including timestamp and version numbers
##            $osm_points : 'sf' Simple Features Collection with 111323 points
##             $osm_lines : 'sf' Simple Features Collection with 34465 linestrings
##          $osm_polygons : 'sf' Simple Features Collection with 618 polygons
##        $osm_multilines : NULL
##     $osm_multipolygons : 'sf' Simple Features Collection with 23 multipolygons

Me quedo con las calles

calles_baires <- Baires$osm_lines
library(ggplot2)
calles_baires <- st_intersection(calles_baires, bbox_pol_caba)
## although coordinates are longitude/latitude, st_intersection assumes that they are planar
## Warning: attribute variables are assumed to be spatially constant
## throughout all geometries
ggplot() +
  geom_sf(data=calles_baires)

Limpiamos el dataframe

calles_baires <- calles_baires %>% 
  mutate(maxspeed = as.numeric(maxspeed),
         lanes = ifelse(is.na(lanes), 1, as.numeric(lanes)))

Ahora puedo ver las velocidades mapeado

ggplot(calles_baires) +
    geom_sf(aes(color = maxspeed), alpha = 0.5) +
    scale_color_viridis_c() +
      theme_void() +
    labs(title = "Buenos Aires",
         subtitle = "Vías de circulación",
         caption = "fuente: OpenStreetMap",
         color = "velocidad máxima")

Ahora puedo ver las calles de doble mano

ggplot(calles_baires) +
    geom_sf(aes(color = lanes), alpha = 0.5) +
    scale_color_viridis_c() +
      theme_void() +
    labs(title = "Buenos Aires",
         subtitle = "Vías de circulación",
         caption = "fuente: OpenStreetMap",
         color = "velocidad máxima")

Voy a elegir bancos y ver como se distribuyen en la ciudad, lo armo en un dataframe nuevo baires_bancos

baires_bancos <- opq(bbox_pol_caba) %>% 
  add_osm_feature(key = "amenity", value = "bank") %>% 
  osmdata_sf() 

Intersecto lineas y puntos para luego hacer en el mapa

baires_bancos <- st_intersection(baires_bancos$osm_points, bbox_pol_caba)
## although coordinates are longitude/latitude, st_intersection assumes that they are planar
## Warning: attribute variables are assumed to be spatially constant
## throughout all geometries
ggplot() +
  geom_sf(data = calles_baires, 
            color = "darkslateblue") +
  geom_sf(data = baires_bancos) +
  geom_sf_label(data = baires_bancos, 
                  aes(label = name), size = 2) +
  theme_void() +
  labs(title = "Buenos Aires",
       subtitle = "Bancos",
       caption = "fuente: OpenStreetMap")
## Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may
## not give correct results for longitude/latitude data
## Warning: Removed 1307 rows containing missing values (geom_label).

barrios <- st_read("http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson")
## Reading layer `barrios_badata' from data source `http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson' using driver `GeoJSON'
## Simple feature collection with 48 features and 4 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -58.53152 ymin: -34.70529 xmax: -58.33515 ymax: -34.52649
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
cantidad <- baires_bancos %>% 
  summarise(cantidad = n())%>%
  st_set_geometry(NULL)

Mapeo por barrios

ggplot() +
  geom_sf(data = barrios) +
  geom_sf(data = baires_bancos, color = "red", alpha = .3)

ahora traigo los gimnasios

gimnasios <- read.csv("~/MEU/MU115 - CIencia de Datos II/gimnasios.csv", header=TRUE)

Ahora los dibujo los dos juntos, ya que uno es “Espacial”, y el otro es un dataset comun.Lo hago con ggplot

ggplot() +
    geom_sf(data = barrios) +
    geom_point(data = gimnasios, 
               aes(x = long, y = lat),
               alpha = .3, 
               color = "red")
## Warning: Removed 4 rows containing missing values (geom_point).

Obviamente no hay mucha relacion entre los gimnasios y los bancos en la ciudad, en el mapa anterior se ve que las sucursales bancarias tienen una distribucion geografica mas relacionada a la actividad comercial, y mas precisamente se ubican preferentemente en la linea de las grandes avenidas, y sobre todo en el area del microcentro (en la city porteña). LA distribucion de los gimnasios parece bastante aleatoria, la mayor cantidad se ubican en el corredor norte de la ciudad, principalmente en los barrios de Palermo, Nuñez, Colegiales y Caballito.

gimnasios <- gimnasios %>%
  select(-barrio) %>%
    filter(!is.na(lat), !is.na(long)) %>% 
    st_as_sf(coords = c("long", "lat"), crs = 4326)
gimnasios_en_barrios <- st_join(gimnasios, barrios)
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
cantidad <- gimnasios_en_barrios %>% 
  group_by(barrio) %>% 
  summarise(cantidad = n())%>%
  st_set_geometry(NULL)
barrios_gimnasios <- left_join(barrios, cantidad)
## Joining, by = "barrio"
ggplot()+
geom_sf(data=barrios_gimnasios, aes(fill=cantidad))

bancos_en_barrios <- st_join(baires_bancos, barrios)
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
## although coordinates are longitude/latitude, st_intersects assumes that they are planar
cantidad_bancos <- bancos_en_barrios %>% 
  group_by(barrio) %>% 
  summarise(cantidad = n())%>%
  st_set_geometry(NULL)
bancos_en_barrios <- left_join(barrios, cantidad_bancos)
## Joining, by = "barrio"

veo que barrio tiene más bancos:

ggplot()+
geom_sf(data=bancos_en_barrios, aes(fill=cantidad))

Comparando los dos mapas que contabilizan la cantidad de amenities x barrio, es mas claro que el barrio que mas bancos posee es San Nicolas, asiento de la City Porteña, y el barrio que mas gimnasios tiene es Palermo. el Barrio que menos bancos tiene es Villa Riachuelo, Coghlan, agronomia y Versalles, mientras que los que menos gimnasios tienen son Coghlan, Villa Ortuzar, Monte Castro, Villa Lugano y Villa Soldati.

Tal vez una buena medida para determinar la distribucion de los gimnasios o bancos en los barrios seria mapear la densidad de cada barrio, ya que en barrios como Villa Ortuzar o Coghlan, la caracteristica es mas residencial, de viviendas unifamiliares, que resulta poco atractivo ubicar un gimnasio o un banco. Ademas habria que revisar las regulaciones de uso del suelo, porque tal vez este relacionado con la normativa.

En los barrios del sur de la ciudad, como Villa Riachuelo, es probable que la situacion de menos seguridad resulte la explicacion a la inexistencia de sucursal bancaria.

TAREA CLASE 3

library(rtweet)
## Warning: package 'rtweet' was built under R version 3.6.1
## 
## Attaching package: 'rtweet'
## The following object is masked from 'package:purrr':
## 
##     flatten
library(tidyverse)

Cargo el csv de los tweets (Cortesia de Soledad Luna ;))

tweetsBA <- read.csv("~/MEU/MU115 - CIencia de Datos II/tweetsBA.csv", encoding = "UTF-8")
users_data(tweetsBA) %>% head()
##        user_id    screen_name
## 1 1.690628e+08        Mar_221
## 2 1.043183e+09         roiggi
## 3 1.161094e+09   VivirporBoca
## 4 3.417911e+08  carlbonifatti
## 5 8.435612e+17      tapochski
## 6 4.015059e+08 victorhugocom1
##                                                       name
## 1                                                      Mar
## 2                                                     gise
## 3                                          Ulises Chaparro
## 4 Carl Bonifatti <U+0001F331> SOS <U+0001F1FB><U+0001F1EA>
## 5                                            Maga campeona
## 6                                          @victorhugo.com
##                         location
## 1                   Buenos Aires
## 2                   Buenos Aires
## 3         Castelar, Buenos Aires
## 4        Buenos Aires, Argentina
## 5 Florencio Varela, Buenos aires
## 6        Buenos Aires, Argentina
##                                                                                                                                     description
## 1 Abogada, no como la kuatrera de Tolosa y por lo mismo no ando con vueltas. El mas degradante invento del siglo es lo “políticamente correcto”
## 2                                                                                                           Ituzaingo y Moron....mis dos amores
## 3                                         Hincha del Boca de Macri. Estudiante Veterinaria UBA. No vuelven más. Que boludos son los comunistas.
## 4                                                          <U+260E> 0800-555-5065 las 24 hs. si ves a alguien organizando saqueos o disturbios.
## 5                                               Fotógrafa, hincha de Racing, marxista hija del argentinazo.\nPortfolio: https://t.co/xxQhO9s03d
## 6                                                                                                                                              
##                       url protected followers_count friends_count
## 1                             FALSE            1528           788
## 2                             FALSE             402          1044
## 3                             FALSE            7912          3390
## 4 https://t.co/UCicQfhWu5     FALSE           75346         39261
## 5 https://t.co/dZYNvI4xs5     FALSE            1964           489
## 6                             FALSE              20           132
##   listed_count statuses_count favourites_count   account_created_at
## 1           23          70450            30659 2010-07-21T13:09:22Z
## 2            1          14961             8655 2012-12-28T21:24:56Z
## 3            7          20148            12781 2013-02-08T20:10:42Z
## 4          281         134387           142941 2011-07-24T23:46:39Z
## 5            9          26445            23227 2017-03-19T20:33:51Z
## 6            0           1579              418 2011-10-30T17:04:25Z
##   verified             profile_url                profile_expanded_url
## 1    FALSE                                                            
## 2    FALSE                                                            
## 3    FALSE                                                            
## 4    FALSE https://t.co/UCicQfhWu5 https://carlbonifatti.wordpress.com
## 5    FALSE https://t.co/dZYNvI4xs5     http://instagram.com/mdefelippe
## 6    FALSE                                                            
##   account_lang
## 1           NA
## 2           NA
## 3           NA
## 4           NA
## 5           NA
## 6           NA
##                                                    profile_banner_url
## 1          https://pbs.twimg.com/profile_banners/169062778/1489984379
## 2         https://pbs.twimg.com/profile_banners/1043183088/1396838777
## 3         https://pbs.twimg.com/profile_banners/1161094200/1385598221
## 4          https://pbs.twimg.com/profile_banners/341791093/1446999637
## 5 https://pbs.twimg.com/profile_banners/843561175778508800/1550706016
## 6          https://pbs.twimg.com/profile_banners/401505895/1506966552
##                              profile_background_url
## 1  http://abs.twimg.com/images/themes/theme1/bg.png
## 2 http://abs.twimg.com/images/themes/theme11/bg.gif
## 3 http://abs.twimg.com/images/themes/theme18/bg.gif
## 4 http://abs.twimg.com/images/themes/theme14/bg.gif
## 5                                                  
## 6  http://abs.twimg.com/images/themes/theme1/bg.png
##                                                             profile_image_url
## 1 http://pbs.twimg.com/profile_images/1088234307737567232/y6vbDrZ0_normal.jpg
## 2 http://pbs.twimg.com/profile_images/472898913926516736/Pe00nWbu_normal.jpeg
## 3 http://pbs.twimg.com/profile_images/1142950745471356930/fVT_exwF_normal.png
## 4  http://pbs.twimg.com/profile_images/647980381363412992/IXcP9pGC_normal.jpg
## 5 http://pbs.twimg.com/profile_images/1151258915151196167/-uiU2hdN_normal.jpg
## 6  http://pbs.twimg.com/profile_images/914909214308519938/_zXonKUR_normal.jpg
names(tweetsBA)
##  [1] "user_id"                 "status_id"              
##  [3] "created_at"              "screen_name"            
##  [5] "text"                    "source"                 
##  [7] "display_text_width"      "reply_to_status_id"     
##  [9] "reply_to_user_id"        "reply_to_screen_name"   
## [11] "is_quote"                "is_retweet"             
## [13] "favorite_count"          "retweet_count"          
## [15] "quote_count"             "reply_count"            
## [17] "hashtags"                "symbols"                
## [19] "urls_url"                "urls_t.co"              
## [21] "urls_expanded_url"       "media_url"              
## [23] "media_t.co"              "media_expanded_url"     
## [25] "media_type"              "ext_media_url"          
## [27] "ext_media_t.co"          "ext_media_expanded_url" 
## [29] "ext_media_type"          "mentions_user_id"       
## [31] "mentions_screen_name"    "lang"                   
## [33] "quoted_status_id"        "quoted_text"            
## [35] "quoted_created_at"       "quoted_source"          
## [37] "quoted_favorite_count"   "quoted_retweet_count"   
## [39] "quoted_user_id"          "quoted_screen_name"     
## [41] "quoted_name"             "quoted_followers_count" 
## [43] "quoted_friends_count"    "quoted_statuses_count"  
## [45] "quoted_location"         "quoted_description"     
## [47] "quoted_verified"         "retweet_status_id"      
## [49] "retweet_text"            "retweet_created_at"     
## [51] "retweet_source"          "retweet_favorite_count" 
## [53] "retweet_retweet_count"   "retweet_user_id"        
## [55] "retweet_screen_name"     "retweet_name"           
## [57] "retweet_followers_count" "retweet_friends_count"  
## [59] "retweet_statuses_count"  "retweet_location"       
## [61] "retweet_description"     "retweet_verified"       
## [63] "place_url"               "place_name"             
## [65] "place_full_name"         "place_type"             
## [67] "country"                 "country_code"           
## [69] "status_url"              "name"                   
## [71] "location"                "description"            
## [73] "url"                     "protected"              
## [75] "followers_count"         "friends_count"          
## [77] "listed_count"            "statuses_count"         
## [79] "favourites_count"        "account_created_at"     
## [81] "verified"                "profile_url"            
## [83] "profile_expanded_url"    "account_lang"           
## [85] "profile_banner_url"      "profile_background_url" 
## [87] "profile_image_url"       "lon"                    
## [89] "lat"
options(scipen = 20)
ggplot(tweetsBA) +
    geom_histogram(aes(x = followers_count))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Top 5 de ,los que mas seguidores tienen:

tweetsBA %>% 
    top_n(5, followers_count) %>% 
    arrange(desc(followers_count)) %>% 
    select(screen_name, followers_count, location, text)
##      screen_name followers_count                location
## 1      ESPNFCarg          447378 Buenos Aires, Argentina
## 2      Lubertino          121297            Buenos Aires
## 3  carlbonifatti           75346 Buenos Aires, Argentina
## 4 CELS_Argentina           69452 Buenos Aires, Argentina
## 5    rayovirtual           47118 Buenos Aires, Argentina
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           text
## 1                                                                                                                                                                                                                                                                                                                                                            #Video | #Ligue1xESPN <U+0001F1EB><U+0001F1F7>\n\nNO LE GUSTÓ NADA\n\nAndré Villas-Boas se mostró enojadísimo por la decisión de Benedetto de agarrar el penal que terminó malogrando.\n\nhttps://t.co/btxcRqIjXZ
## 2                                                                                                                                                                                                                                                                                                                                                                              #Ahora en #BarrioCarrillo #Comuna8 en reunión con referentes de villas y @UNICEFargentina en diálogo sobre #violenciainstitucional en relación a #niñes y #adolescentes https://t.co/4Pyo5QomXr
## 3                                                                                                                                                                                                                                                                                                                                                                                                                Cristóbal López con el guiño de Cristina y Máximo financia un estallido social, inyectando dinero en las Villas para movilizar a sus habitantes. #PorotaTajai
## 4 <U+0001D5D6><U+0001D5EE><U+0001D600><U+0001D5EE><U+0001D600> <U+0001D600><U+0001D5F6><U+0001D5FB> <U+0001D5F4><U+0001D5F2><U+0001D5FB><U+0001D601><U+0001D5F2>/ <U+0001D5DA><U+0001D5F2><U+0001D5FB><U+0001D601><U+0001D5F2> <U+0001D600><U+0001D5F6><U+0001D5FB> <U+0001D5F0><U+0001D5EE><U+0001D600><U+0001D5EE><U+0001D600>\nSegún datos oficiales el 9,2% de las viviendas de la ciudad de Bs. As están vacías.\n\n<U+2757><U+FE0F>138.328 casas y departamentos.\n\nMientras que:\n-300.000 personas viven en villas y asentamientos\n-7500 están en situación de calle
## 5                                                                                                                                                                                                                                                                               @Ricardo_blogger No. Por un lado quieren satisfacer al cliente (y muchos trabajan para Alberto), pero por otro quieren acertar porque pierden prestigio y trabajo futuro.\nEs que usar el teléfono es más barato que mandar gente a las villas y barrios pobres (mucho más barato) y eso pesa.

Me quedo con los tweets originales, eliminando los retweets

ggplot(filter(tweetsBA, !is_retweet))+
    geom_histogram(aes(x = retweet_count))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

el que mas seguidores tiene:

tweetsBA %>% 
    filter(!is_retweet) %>% 
    filter(retweet_count == max(retweet_count)) %>% 
    select(screen_name, retweet_count, followers_count, location, text)
##   screen_name retweet_count followers_count                location
## 1    belumita           739            8049 Buenos Aires, Argentina
##                                                                                                                                                                                                                                                           text
## 1 USTEDES ENTIENDEN QUE VA A MANEJAR LA PROVINCIA (centro de pobreza, corrupción y villas) UN TIPO QUE DICE QUE \n\n“La inflación NO ES un fenómeno monetario” ??????\n\nY quien manejaba LA MATANZA, irónicamente el centro de homicidios de Bs As. Infierno.

Distribucion horaria de los tweets

library(lubridate)
## Warning: package 'lubridate' was built under R version 3.6.1
## 
## Attaching package: 'lubridate'
## The following object is masked from 'package:base':
## 
##     date
tweetsBA <- tweetsBA %>%
  mutate(created_at = ymd_hms(created_at))


tweetsBA %>% 
  group_by(hour = hour(created_at)) %>% 
  summarise(total = n()) %>% 
  ggplot() +
  geom_path(aes(x = hour, y = total))

tweetsBA %>% 
  group_by(dia_hora = floor_date(created_at, "hour")) %>% 
  summarise(total = n()) %>% 
  ggplot() +
  geom_path(aes(x = dia_hora, y = total))

library(ggmap)
## Warning: package 'ggmap' was built under R version 3.6.1
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.

Mapeamos los tweets

coordenadasBA <- function(campo_coordenadas) {
    extraer_coordenadas <- function(lista_coords) {
        data_frame(lon = lista_coords[1],
                   lat = lista_coords[2])
    }
    
    map_df(campo_coordenadas, extraer_coordenadas)
}

No me permite hacer nada, porque los tweets no tienen coordenadas…

tweetsBA_geo <- tweetsBA %>% 
    filter(!is.na(lat), !is.na(lon))

Intente hacer el data table, pero igual tardaba mucho y luego me trae problemas con el lubridate.

TAREA CLASE 4

library(tidyverse)
library(lubridate)

Trabajamos con patrones de tiempo y espacio. Data elegida: Operativos Defensa Civil BA, año 2018

operativos.2018 <- read.csv("~/MEU/MU115 - CIencia de Datos II/operativos-2018.csv")
names(operativos.2018)
##  [1] "long"                    "lat"                    
##  [3] "fecha"                   "suceso"                 
##  [5] "calle_nombre"            "calle_altura"           
##  [7] "barrio"                  "comuna"                 
##  [9] "observacion"             "movil"                  
## [11] "a_cargo"                 "turno"                  
## [13] "emergencia"              "prevencion"             
## [15] "amenaza"                 "mes"                    
## [17] "codigo_postal"           "codigo_postal_argentino"
summary(operativos.2018)
##       long             lat                fecha     
##  Min.   :-58.53   Min.   :-34.70   2018-12-13: 119  
##  1st Qu.:-58.47   1st Qu.:-34.64   2018-12-30: 115  
##  Median :-58.43   Median :-34.63   2018-12-14:  79  
##  Mean   :-58.43   Mean   :-34.63   2018-05-10:  70  
##  3rd Qu.:-58.39   3rd Qu.:-34.61   2018-05-02:  69  
##  Max.   :-58.34   Max.   :-34.53   2018-08-09:  69  
##                                    (Other)   :9384  
##                                                    suceso    
##  ARBOLES / RAMAS                                      :1830  
##  PELIGRO DE CAIDA COLUMNA / POSTE / CARTEL / LUMINARIA:1268  
##  CABLES EXPUESTOS / CAIDOS                            :1164  
##  ESCAPE DE GAS                                        :1067  
##  RIESGO ELECTRICO                                     : 661  
##  INCENDIO                                             : 548  
##  (Other)                                              :3367  
##                    calle_nombre   calle_altura            barrio    
##  RIVADAVIA               : 185   Min.   :    0   BALVANERA   : 674  
##  ALBERDI JUAN BAUTISTA AV:  65   1st Qu.:    0   FLORES      : 673  
##  INDEPENDENCIA AV        :  63   Median : 1038   BARRACAS    : 595  
##  SAN JUAN                :  53   Mean   : 1683   VILLA LUGANO: 579  
##  CORRIENTES              :  50   3rd Qu.: 2671   CABALLITO   : 547  
##  FALCON RAMON L.CNEL.    :  48   Max.   :16100   MATADEROS   : 425  
##  (Other)                 :9441                   (Other)     :6412  
##       comuna                           observacion       movil     
##  COMUNA 4:1645                               :3764   Min.   :   0  
##  COMUNA 1:1324   S/NOVEDAD                   : 596   1st Qu.: 140  
##  COMUNA 9:1000   SIN NOVEDAD                 : 511   Median : 303  
##  COMUNA 7: 997   SE SEÑALIZA SE PASA AL CUCC: 210   Mean   : 393  
##  COMUNA 8: 985   SE PASA AL CUCC             : 142   3rd Qu.: 797  
##  COMUNA 3: 928   S/ NOVEDAD                  : 135   Max.   :8550  
##  (Other) :3026   (Other)                     :4547                 
##     a_cargo     turno      emergencia prevencion
##  ALARCON: 431      : 112   no: 413    no:9492   
##  BERARDI: 316   F/S:2060   si:9492    si: 413   
##  CASCO  : 301   TM :2842                        
##  SANZ   : 264   TN :2178                        
##  LIO    : 257   TT :2713                        
##  ENRIQUE: 249                                   
##  (Other):8087                                   
##                                       amenaza            mes      
##  OTROS                                    :5902   DICIEMBRE:1167  
##  13) INTERRUPCION DE SERVICIOS BASICOS    :1528   AGOSTO   : 959  
##  7) FUGA DE GAS                           : 671   ENERO    : 944  
##  14) INTOXICACIONES Y CONTAMINACIONES     : 541   NOVIEMBRE: 865  
##  1) LLUVIAS TORRENCIALES Y FUERTES VIENTOS: 419   MAYO     : 853  
##  3) INCENDIOS                             : 414   ABRIL    : 770  
##  (Other)                                  : 430   (Other)  :4347  
##  codigo_postal  codigo_postal_argentino
##  Min.   :1001           :2889          
##  1st Qu.:1199   C1405CVH:  20          
##  Median :1406   C1160ACD:  14          
##  Mean   :1311   C1272ADF:  12          
##  3rd Qu.:1425   C1416DGM:  12          
##  Max.   :1440   C1282AFF:  10          
##  NA's   :2883   (Other) :6948

Cambiamos la fecha

operativos.2018 <- operativos.2018 %>%
  mutate(fecha=ymd(fecha))

Tomamos una muestra al azar de cinco fechas

set.seed("99")
muestra_de_fechas <- operativos.2018 %>% 
    sample_n(5) %>% 
    pull(fecha)

muestra_de_fechas
## [1] "2018-08-03" "2018-10-13" "2018-03-26" "2018-04-21" "2018-09-30"

Hago un histograma con cantidad de operativos por mes, ya que le dataset es del año 2018

operativos.2018 %>% 
    filter(year(fecha) == 2018) %>% 
    ggplot()+
    geom_bar(aes(x = month(fecha, label = TRUE)))

Lo graficamos por tipo de operativo:

operativos.2018 %>% 
    count(suceso) %>% 
    top_n(5) %>% 
    arrange(desc(n))
## Selecting by n
## # A tibble: 5 x 2
##   suceso                                                    n
##   <fct>                                                 <int>
## 1 ARBOLES / RAMAS                                        1830
## 2 PELIGRO DE CAIDA COLUMNA / POSTE / CARTEL / LUMINARIA  1268
## 3 CABLES EXPUESTOS / CAIDOS                              1164
## 4 ESCAPE DE GAS                                          1067
## 5 RIESGO ELECTRICO                                        661
operativos_frecuentes <- operativos.2018 %>% 
    count(suceso) %>% 
    top_n(5) %>% 
    pull(suceso)
## Selecting by n
operativos.2018 %>% 
    filter(year(fecha) == 2018,
           suceso %in% operativos_frecuentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha, label = TRUE), fill = suceso))

En grafico de barras

operativos.2018 %>% 
    filter(year(fecha) == 2018,
           suceso %in% operativos_frecuentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha, label = TRUE), fill = suceso),
                 position = "dodge")

El suceso mas comun es la caida de ramas y arboles, en los meses de Enero, Noviembre y la mayoria se produjo en Diciembre. Supongo que el patron temporal de dicah distribucion tendra que ver con las lluvias que cayeron en la ciudad, seguramente han sido mas copiosas en esos meses de verano. La mayor cantidad de operativos en relacion a escapes de gas se dieron en el mes de Agosto, epoca invernal.

Quiero saber que agente estuvo a cargo en los operativos

operativos.2018 %>% 
    count(a_cargo) %>% 
    top_n(5) %>% 
    arrange(desc(n))
## Selecting by n
## # A tibble: 5 x 2
##   a_cargo     n
##   <fct>   <int>
## 1 ALARCON   431
## 2 BERARDI   316
## 3 CASCO     301
## 4 SANZ      264
## 5 LIO       257

Creo otro dataset con los agentes a cargo

operativos_agentes <- operativos.2018 %>% 
    count(a_cargo) %>% 
    top_n(5) %>% 
    pull(a_cargo)
## Selecting by n
operativos.2018 %>% 
    filter(year(fecha) == 2018,
           a_cargo %in% operativos_agentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha, label = TRUE), fill = a_cargo))

operativos.2018 %>% 
    filter(year(fecha) == 2018,
           a_cargo %in% operativos_agentes) %>% 
    ggplot() +
        geom_bar(aes(x = month(fecha, label = TRUE), fill = a_cargo),
                 position = "dodge")

Un patron temporal para los agentes a cargo, puede estar relacionado con muchas variables, el agente Alarcon estuvo a cargo de mas cantidad de operativos en los meses de mayo y noviembre, el agente Casco su mayor participacion fue en el mes de enero, y el agente Lio tuvo participacion minima en el mes de noviembre (Cuando Alarcon tuvo su mayor participacion) ESte ultima situacion podria pensarse como un reemplazo por enfermedad o vacaciones, o licencia de algun otro tipo del agente Lio, que fue reemplazado por el Agente Alarcon.

GRafico de lineas por tipo de operativo:

conteo_operativos <-  operativos.2018 %>% 
    filter(year(fecha) == 2018,
           suceso %in% operativos_frecuentes) %>% 
    count(suceso, mes = month(fecha, label = TRUE))
ggplot(conteo_operativos) +
    geom_line(aes(x = mes, y = n, group = suceso, color = suceso))+
  geom_point(aes(x = mes, y = n, group = suceso, color = suceso, size = 0.05))+
  scale_color_brewer(palette = "set1")+
  labs(title="Top 5 de operativos 2018", 
       color="tipo de operativo",
       x="meses",
       y = "Cantidad")+
  theme_minimal()
## Warning in pal_name(palette, type): Unknown palette set1

Armo un mapa con el tipo de operativos para distribuir geograficamente

library(ggmap)
operativos.2018 <- operativos.2018 %>% 
    filter(lat <0, long <0)

bbox <- c(min(operativos.2018$long, na.rm = TRUE),
          min(operativos.2018$lat, na.rm = TRUE),
          max(operativos.2018$long, na.rm = TRUE),
          max(operativos.2018$lat, na.rm = TRUE))
library(osmdata)
bbox <- getbb("Ciudad Autonoma de Buenos Aires")
bbox
##         min       max
## x -58.53146 -58.33512
## y -34.70564 -34.52655
CABA <- get_stamenmap(bbox = bbox,
                      maptype="toner-lite",
                      zoom=13)
## Source : http://tile.stamen.com/toner-lite/13/2764/4934.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4934.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4934.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4934.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4934.png
## Source : http://tile.stamen.com/toner-lite/13/2764/4935.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4935.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4935.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4935.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4935.png
## Source : http://tile.stamen.com/toner-lite/13/2764/4936.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4936.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4936.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4936.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4936.png
## Source : http://tile.stamen.com/toner-lite/13/2764/4937.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4937.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4937.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4937.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4937.png
## Source : http://tile.stamen.com/toner-lite/13/2764/4938.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4938.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4938.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4938.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4938.png
## Source : http://tile.stamen.com/toner-lite/13/2764/4939.png
## Source : http://tile.stamen.com/toner-lite/13/2765/4939.png
## Source : http://tile.stamen.com/toner-lite/13/2766/4939.png
## Source : http://tile.stamen.com/toner-lite/13/2767/4939.png
## Source : http://tile.stamen.com/toner-lite/13/2768/4939.png
ggmap(CABA)

Puntos por cantidad de operativos

ggmap(CABA) +
    geom_point(data = operativos.2018, aes(x = long, y = lat),
               color = "green", size = 0.5, alpha = 0.1)

Mapa de calor x cantidad de operativos

ggmap(CABA) +
    geom_bin2d(data = operativos.2018, 
               aes(x = long, y = lat), bins=75)+
  scale_fill_viridis_c()

Isolineas cantidad de operativos

ggmap(CABA) +
    geom_density2d(data = operativos.2018, aes(x = long, y = lat, color = stat(level))) +
    scale_color_viridis_c()

Mapeo por tipo de operativo

ggmap(CABA) +
    geom_point(data = filter(operativos.2018, suceso %in% operativos_frecuentes), 
               aes(x = long, y = lat, color = suceso),
               size = 0.5, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size=2, alpha = 1))) +
    scale_color_brewer(palette = "Set1")

La primera conclusion de haber puesto la cantidad y tipo de operativo en un mapa de la ciudad, queda demosatrado que los operativos se concentran en el area sur de la ciudad, de la avenida Rivadavia hacia el sur. Supongo que tendra que ver con que se denuncian mas sucesos en los cuales defensa civil de la ciudad debe actuar en esa zonas.

Mapeo facetado por tipo de operativo en la ciudad

ggmap(CABA) +
    geom_point(data = filter(operativos.2018, suceso %in% operativos_frecuentes), 
               aes(x = long, y = lat, color = suceso),
               size = 0.5, alpha = 0.1) +
    guides(color = guide_legend(override.aes = list(size=2, alpha = 1))) +
    scale_color_brewer(palette = "Set1") +
    facet_wrap(~suceso)

Facetado con densidad por tipo de operativo

ggmap(CABA) +
    geom_density2d(data = filter(operativos.2018, suceso %in% operativos_frecuentes), aes(x = long, y = lat, color = stat(level))) +
    scale_color_viridis_c() +
    facet_wrap(~suceso)

El suceso que se distribuye un poco mas uniformemente en la ciudad es el “escape de Gas”. El suceso “riesgo electrico” es bastante mas tenue en intensidad, que el resto de los sucesos.

operativos.2018 <- operativos.2018 %>%
  mutate(dia=wday(fecha, label=TRUE))
ggmap(CABA) +
    geom_density2d(data = filter(operativos.2018, suceso %in% operativos_frecuentes), aes(x = long, y = lat, color = stat(level))) +
    scale_color_viridis_c() +
    facet_wrap(~dia, nrow=2)

Los dias domingo y lunes los operativos son mayores, tal vez porque hay mas denuncias para que defensa civil de la ciudad acuda a los llamados.

TAREA CLASE 5

barrios <- st_read("http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson")
## Reading layer `barrios_badata' from data source `http://cdn.buenosaires.gob.ar/datosabiertos/datasets/barrios/barrios.geojson' using driver `GeoJSON'
## Simple feature collection with 48 features and 4 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -58.53152 ymin: -34.70529 xmax: -58.33515 ymax: -34.52649
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
 bici19_cdn <- read.csv("~/MEU/MU115 - CIencia de Datos II/bici19_cdn.csv", encoding = "UTF-8")
names(bici19_cdn)
## [1] "bici_id_usuario"              "bici_Fecha_hora_retiro"      
## [3] "bici_tiempo_uso"              "bici_nombre_estacion_origen" 
## [5] "bici_estacion_origen"         "bici_nombre_estacion_destino"
## [7] "bici_estacion_destino"        "bici_sexo"                   
## [9] "bici_edad"
summary(bici19_cdn)
##  bici_id_usuario          bici_Fecha_hora_retiro bici_tiempo_uso 
##  Min.   :    33   2019-01-07 20:13:12:     4     Min.   :  0.00  
##  1st Qu.:177438   2019-01-11 14:58:09:     4     1st Qu.:  8.00  
##  Median :375196   2019-01-14 12:50:25:     4     Median : 14.00  
##  Mean   :359739   2019-01-16 15:54:47:     4     Mean   : 16.51  
##  3rd Qu.:547898   2019-01-17 14:16:34:     4     3rd Qu.: 21.00  
##  Max.   :693680   2019-01-25 08:21:43:     4     Max.   :118.00  
##                   (Other)            :204083     NA's   :131     
##           bici_nombre_estacion_origen bici_estacion_origen
##  Vera Peñaloza          :  3092       Min.   :  1.0       
##  Facultad de Medicina   :  3046       1st Qu.: 54.0       
##  Independencia          :  2902       Median : 98.0       
##  Lima                   :  2781       Mean   :100.5       
##  Godoy Cruz y Libertador:  2600       3rd Qu.:149.0       
##  Don Bosco              :  2526       Max.   :600.0       
##  (Other)                :187160                           
##        bici_nombre_estacion_destino bici_estacion_destino
##  Vera Peñaloza       :  3091        Min.   :  1.0        
##  Facultad de Medicina:  3040        1st Qu.: 55.0        
##  Independencia       :  2698        Median : 99.0        
##  Lima                :  2663        Mean   :101.2        
##  Saavedra            :  2600        3rd Qu.:149.0        
##  Don Bosco           :  2523        Max.   :600.0        
##  (Other)             :187492        NA's   :131          
##         bici_sexo        bici_edad    
##  FEMENINO    : 54268   Min.   :16.00  
##  MASCULINO   :149804   1st Qu.:25.00  
##  NO INFORMADO:    35   Median :30.00  
##                        Mean   :33.26  
##                        3rd Qu.:39.00  
##                        Max.   :87.00  
## 

Descargo mapa estaciones de bicicleta

estaciones <- read.csv("https://bitsandbricks.github.io/data/estaciones_BA_bici.csv")
ggplot() +
    geom_sf(data = barrios) +
    geom_point(data = estaciones, 
               aes(x = X, y = Y),
               alpha = .3, 
               color = "red")

library(ggmap)

bbox <- make_bbox(estaciones$X, estaciones$Y)

bbox
##      left    bottom     right       top 
## -58.46000 -34.64541 -58.35132 -34.56439
mapa_base <- get_stamenmap(bbox, color = "bw", zoom = 12)
## Source : http://tile.stamen.com/terrain/12/1382/2467.png
## Source : http://tile.stamen.com/terrain/12/1383/2467.png
## Source : http://tile.stamen.com/terrain/12/1384/2467.png
## Source : http://tile.stamen.com/terrain/12/1382/2468.png
## Source : http://tile.stamen.com/terrain/12/1383/2468.png
## Source : http://tile.stamen.com/terrain/12/1384/2468.png
ggmap(mapa_base) +
    geom_point(data = estaciones, aes(x = X, y = Y), color = "blue") +
    theme_nothing()

conteo <- bici19_cdn %>% 
    group_by(bici_estacion_origen, bici_estacion_destino) %>% 
    summarise(cantidad=n())

Hago un heat map

ggplot() + 
    geom_tile(data = conteo, aes(x = bici_estacion_origen, y = bici_estacion_destino, fill = cantidad)) +
    scale_fill_distiller(palette = "Spectral")
## Warning: Removed 67 rows containing missing values (geom_tile).

top10 <- conteo %>% 
    ungroup() %>% 
    filter(bici_estacion_origen != bici_estacion_destino) %>% 
    arrange(desc(cantidad)) %>% 
    top_n(10)
## Selecting by cantidad
top10
## # A tibble: 10 x 3
##    bici_estacion_origen bici_estacion_destino cantidad
##                   <int>                 <dbl>    <int>
##  1                  150                    18      238
##  2                   18                   150      233
##  3                  160                   156      198
##  4                  149                   150      195
##  5                  150                   149      170
##  6                    1                   189      164
##  7                   16                   150      163
##  8                    1                   103      160
##  9                  146                    86      159
## 10                  156                   160      156

Descartamos los viajes circulares:

ggplot() + 
    geom_tile(data = top10, 
              aes(x = as.factor(bici_estacion_origen),
                  y = as.factor(bici_estacion_destino),
                  fill = cantidad)) +
    scale_fill_distiller(palette = "Spectral")

Segun el tile map que acabamos de hacer, los recorridos entre la estacion 150 (Vera Peñaloza y Olga Cosettini) y la 18 (Av Independencia y Av 9 de Julio) son los mas frecuentes.

library(osrm)
## Warning: package 'osrm' was built under R version 3.6.1
## Data: (c) OpenStreetMap contributors, ODbL 1.0 - http://www.openstreetmap.org/copyright
## Routing: OSRM - http://project-osrm.org/

Rutas mas frecuentes: 1º) Av Independencia y 9 de Julio a Olga Cossettini y Vera Peñaloza 2º) Igual a 1º

independencia <- c(nombre = "independencia",
                 lon = -58.38048,
                 lat = -34.61737)       

cossetini <- c(nombre = "cossetini",
             lon = -58.36309,       
             lat = -34.61808)

independencia_a_cossetini <- osrmRoute(src = independencia, 
                                 dst = cossetini, 
                                 returnclass = "sf", 
                                 overview = "full")
library(leaflet)

leaflet(independencia_a_cossetini) %>% 
    addTiles() %>% 
    addPolylines(color = "red")

3º) 160 GODOY CRUZ Y LIBERTADOR a 156 (Plaza Alemania)

godoy_cruz <- c(nombre = "godoy_cruz",
                 lon = -58.42021,
                 lat = -34.57296)       

p_alemania <- c(nombre = "p_alemania",
             lon = -58.40797,       
             lat = -34.57785)

godoy_cruz_a_p_alemania <- osrmRoute(src = godoy_cruz, 
                                 dst = p_alemania, 
                                 returnclass = "sf", 
                                 overview = "full")
leaflet(godoy_cruz_a_p_alemania) %>% 
    addTiles() %>% 
    addPolylines(color = "red")

Agrego las coordenadas de estaciones de origen y destino al los recorridos top10

top10 <- top10 %>% 
    left_join(estaciones[c("X", "Y", "NOMBRE", "NRO_EST")], 
              by = c("bici_estacion_origen" = "NRO_EST")) %>% 
    rename(ORIGEN_X = X,
           ORIGEN_Y = Y,
           bici_nombre_estacion_origen = NOMBRE)

top10
## # A tibble: 10 x 6
##    bici_estacion_o~ bici_estacion_d~ cantidad ORIGEN_X ORIGEN_Y
##               <int>            <dbl>    <int>    <dbl>    <dbl>
##  1              150               18      238    -58.4    -34.6
##  2               18              150      233    -58.4    -34.6
##  3              160              156      198    -58.4    -34.6
##  4              149              150      195    -58.4    -34.6
##  5              150              149      170    -58.4    -34.6
##  6                1              189      164    -58.4    -34.6
##  7               16              150      163    -58.4    -34.6
##  8                1              103      160    -58.4    -34.6
##  9              146               86      159    -58.4    -34.6
## 10              156              160      156    -58.4    -34.6
## # ... with 1 more variable: bici_nombre_estacion_origen <fct>
top10 <- top10 %>% 
    left_join(unique(estaciones[c("X", "Y", "NOMBRE", "NRO_EST")]), 
              by = c("bici_estacion_destino" = "NRO_EST")) %>% 
    rename(DESTINO_X = X,
           DESTINO_Y = Y,
           bici_nombre_estacion_destino = NOMBRE)

top10
## # A tibble: 10 x 9
##    bici_estacion_o~ bici_estacion_d~ cantidad ORIGEN_X ORIGEN_Y
##               <int>            <dbl>    <int>    <dbl>    <dbl>
##  1              150               18      238    -58.4    -34.6
##  2               18              150      233    -58.4    -34.6
##  3              160              156      198    -58.4    -34.6
##  4              149              150      195    -58.4    -34.6
##  5              150              149      170    -58.4    -34.6
##  6                1              189      164    -58.4    -34.6
##  7               16              150      163    -58.4    -34.6
##  8                1              103      160    -58.4    -34.6
##  9              146               86      159    -58.4    -34.6
## 10              156              160      156    -58.4    -34.6
## # ... with 4 more variables: bici_nombre_estacion_origen <fct>,
## #   DESTINO_X <dbl>, DESTINO_Y <dbl>, bici_nombre_estacion_destino <fct>

Pruebo con procedimiento iterativo

obtener_recorrido <- 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))
    
    cbind(bici_estacion_origen = o_nombre, bici_estacion_destino = d_nombre, ruta)
    
}


argumentos <- list(top10$bici_estacion_origen, top10$ORIGEN_X, top10$ORIGEN_Y,
                  top10$bici_estacion_destino, top10$DESTINO_X, top10$DESTINO_Y)

recorridos<- pmap_df(argumentos, obtener_recorrido) 
recorridos
##     bici_estacion_origen bici_estacion_destino       lon       lat
## 1                    150                    18 -58.36291 -34.61804
## 2                    150                    18 -58.36295 -34.61793
## 3                    150                    18 -58.36267 -34.61801
## 4                    150                    18 -58.36170 -34.61796
## 5                    150                    18 -58.36163 -34.61771
## 6                    150                    18 -58.36174 -34.61748
## 7                    150                    18 -58.36284 -34.61756
## 8                    150                    18 -58.36309 -34.61774
## 9                    150                    18 -58.36344 -34.61785
## 10                   150                    18 -58.36573 -34.61804
## 11                   150                    18 -58.36591 -34.61686
## 12                   150                    18 -58.36659 -34.61687
## 13                   150                    18 -58.36609 -34.62150
## 14                   150                    18 -58.36633 -34.62181
## 15                   150                    18 -58.36656 -34.62196
## 16                   150                    18 -58.36744 -34.62201
## 17                   150                    18 -58.36919 -34.62237
## 18                   150                    18 -58.37058 -34.62236
## 19                   150                    18 -58.37431 -34.62281
## 20                   150                    18 -58.37623 -34.62287
## 21                   150                    18 -58.37917 -34.62263
## 22                   150                    18 -58.37978 -34.62246
## 23                   150                    18 -58.38013 -34.62220
## 24                   150                    18 -58.38038 -34.62168
## 25                   150                    18 -58.38058 -34.62027
## 26                   150                    18 -58.38067 -34.61738
## 27                    18                   150 -58.38067 -34.61738
## 28                    18                   150 -58.38078 -34.61525
## 29                    18                   150 -58.37320 -34.61485
## 30                    18                   150 -58.36947 -34.61478
## 31                    18                   150 -58.36686 -34.61457
## 32                    18                   150 -58.36645 -34.61813
## 33                    18                   150 -58.36344 -34.61785
## 34                    18                   150 -58.36277 -34.61800
## 35                    18                   150 -58.36186 -34.61797
## 36                    18                   150 -58.36143 -34.62127
## 37                    18                   150 -58.36254 -34.62135
## 38                    18                   150 -58.36291 -34.61804
## 39                   160                   156 -58.42075 -34.57276
## 40                   160                   156 -58.42046 -34.57223
## 41                   160                   156 -58.42323 -34.57108
## 42                   160                   156 -58.42362 -34.57076
## 43                   160                   156 -58.42362 -34.57061
## 44                   160                   156 -58.42186 -34.56864
## 45                   160                   156 -58.42081 -34.56685
## 46                   160                   156 -58.41987 -34.56573
## 47                   160                   156 -58.41959 -34.56503
## 48                   160                   156 -58.41661 -34.56270
## 49                   160                   156 -58.41185 -34.56513
## 50                   160                   156 -58.40878 -34.56703
## 51                   160                   156 -58.40854 -34.56731
## 52                   160                   156 -58.40848 -34.56760
## 53                   160                   156 -58.40869 -34.56803
## 54                   160                   156 -58.41125 -34.57096
## 55                   160                   156 -58.41207 -34.57214
## 56                   160                   156 -58.41105 -34.57265
## 57                   160                   156 -58.41010 -34.57358
## 58                   160                   156 -58.40860 -34.57447
## 59                   160                   156 -58.40808 -34.57512
## 60                   160                   156 -58.40797 -34.57500
## 61                   160                   156 -58.40610 -34.57616
## 62                   160                   156 -58.40704 -34.57723
## 63                   149                   150 -58.38144 -34.61529
## 64                   149                   150 -58.38124 -34.61527
## 65                   149                   150 -58.38098 -34.62216
## 66                   149                   150 -58.38131 -34.62260
## 67                   149                   150 -58.38137 -34.62287
## 68                   149                   150 -58.38114 -34.62337
## 69                   149                   150 -58.38067 -34.62358
## 70                   149                   150 -58.38028 -34.62356
## 71                   149                   150 -58.37908 -34.62312
## 72                   149                   150 -58.37812 -34.62298
## 73                   149                   150 -58.37509 -34.62301
## 74                   149                   150 -58.37394 -34.62293
## 75                   149                   150 -58.37170 -34.62264
## 76                   149                   150 -58.36898 -34.62272
## 77                   149                   150 -58.36790 -34.62269
## 78                   149                   150 -58.36677 -34.62246
## 79                   149                   150 -58.36608 -34.62256
## 80                   149                   150 -58.36573 -34.62253
## 81                   149                   150 -58.36532 -34.62230
## 82                   149                   150 -58.36573 -34.61804
## 83                   149                   150 -58.36344 -34.61785
## 84                   149                   150 -58.36277 -34.61800
## 85                   149                   150 -58.36186 -34.61797
## 86                   149                   150 -58.36143 -34.62127
## 87                   149                   150 -58.36254 -34.62135
## 88                   149                   150 -58.36291 -34.61804
## 89                   150                   149 -58.36291 -34.61804
## 90                   150                   149 -58.36295 -34.61793
## 91                   150                   149 -58.36267 -34.61801
## 92                   150                   149 -58.36170 -34.61796
## 93                   150                   149 -58.36163 -34.61771
## 94                   150                   149 -58.36174 -34.61748
## 95                   150                   149 -58.36284 -34.61756
## 96                   150                   149 -58.36309 -34.61774
## 97                   150                   149 -58.36344 -34.61785
## 98                   150                   149 -58.36573 -34.61804
## 99                   150                   149 -58.36591 -34.61686
## 100                  150                   149 -58.36742 -34.61693
## 101                  150                   149 -58.36942 -34.61713
## 102                  150                   149 -58.37167 -34.61721
## 103                  150                   149 -58.37309 -34.61717
## 104                  150                   149 -58.37985 -34.61761
## 105                  150                   149 -58.38304 -34.61773
## 106                  150                   149 -58.38309 -34.61538
## 107                  150                   149 -58.38144 -34.61529
## 108                    1                   189 -58.39256 -34.58330
## 109                    1                   189 -58.40010 -34.57973
## 110                    1                   189 -58.40251 -34.57830
## 111                    1                   189 -58.40488 -34.57658
## 112                    1                   189 -58.40142 -34.57281
## 113                    1                   189 -58.40148 -34.57253
## 114                    1                   189 -58.40197 -34.57212
## 115                    1                   189 -58.40174 -34.57164
## 116                    1                   189 -58.40122 -34.57163
## 117                    1                   189 -58.39907 -34.57253
## 118                    1                   189 -58.39462 -34.57481
## 119                    1                   189 -58.39358 -34.57519
## 120                    1                   189 -58.39232 -34.57595
## 121                    1                   189 -58.39106 -34.57710
## 122                    1                   189 -58.38826 -34.57919
## 123                    1                   189 -58.38156 -34.58273
## 124                    1                   189 -58.38058 -34.58337
## 125                    1                   189 -58.38003 -34.58420
## 126                    1                   189 -58.37994 -34.58513
## 127                    1                   189 -58.38092 -34.58714
## 128                    1                   189 -58.38135 -34.58768
## 129                    1                   189 -58.38193 -34.58799
## 130                    1                   189 -58.38239 -34.58800
## 131                    1                   189 -58.38480 -34.58692
## 132                    1                   189 -58.38501 -34.58704
## 133                    1                   189 -58.38383 -34.58769
## 134                    1                   189 -58.38492 -34.58876
## 135                    1                   189 -58.38554 -34.58841
## 136                   16                   150 -58.37459 -34.61006
## 137                   16                   150 -58.37338 -34.60904
## 138                   16                   150 -58.36964 -34.60889
## 139                   16                   150 -58.36949 -34.61778
## 140                   16                   150 -58.36923 -34.61839
## 141                   16                   150 -58.36344 -34.61785
## 142                   16                   150 -58.36277 -34.61800
## 143                   16                   150 -58.36186 -34.61797
## 144                   16                   150 -58.36143 -34.62127
## 145                   16                   150 -58.36254 -34.62135
## 146                   16                   150 -58.36291 -34.61804
## 147                    1                   103 -58.39256 -34.58330
## 148                    1                   103 -58.39991 -34.57983
## 149                    1                   103 -58.40251 -34.57830
## 150                    1                   103 -58.40362 -34.57750
## 151                  146                    86 -58.40780 -34.62216
## 152                  146                    86 -58.40911 -34.62240
## 153                  146                    86 -58.40885 -34.62460
## 154                  146                    86 -58.40706 -34.62440
## 155                  146                    86 -58.40096 -34.62361
## 156                  146                    86 -58.40165 -34.62135
## 157                  156                   160 -58.40704 -34.57723
## 158                  156                   160 -58.40603 -34.57782
## 159                  156                   160 -58.40488 -34.57658
## 160                  156                   160 -58.40580 -34.57580
## 161                  156                   160 -58.40780 -34.57437
## 162                  156                   160 -58.41096 -34.57219
## 163                  156                   160 -58.41147 -34.57194
## 164                  156                   160 -58.41181 -34.57183
## 165                  156                   160 -58.41231 -34.57217
## 166                  156                   160 -58.41428 -34.57416
## 167                  156                   160 -58.41537 -34.57478
## 168                  156                   160 -58.41540 -34.57509
## 169                  156                   160 -58.41566 -34.57563
## 170                  156                   160 -58.41726 -34.57737
## 171                  156                   160 -58.41805 -34.57650
## 172                  156                   160 -58.41835 -34.57585
## 173                  156                   160 -58.42002 -34.57631
## 174                  156                   160 -58.42237 -34.57549
## 175                  156                   160 -58.42075 -34.57276
recorridos <- recorridos %>% 
    mutate(ID = paste(bici_estacion_origen, "-", bici_estacion_destino))

Mapa de los 10 recorridos mas frecuentes

ggmap(mapa_base) +
    geom_path(data = recorridos, aes(x = lon, y = lat, color = ID)) +
    theme_nothing()

THAT´s ALL FOLKS!!