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))