#Carga de Librerías

library(tidyverse)  # Paquete multiuso
## -- Attaching packages ----------------------------------------------------------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.2     v purrr   0.3.4
## v tibble  3.0.3     v dplyr   1.0.0
## v tidyr   1.1.0     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)  # Paquete clave para manipular datos espaciales
## Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(leaflet)  # Uno de los paquetes para 
library(sf)
library(dplyr)

#Cargamos shape de calles

calles <- read_sf("D:/Documents/01-Ditella/Instrumentos de Analisis Urbano II/callejero-rar/callejero.shp")
st_crs(calles)
## Coordinate Reference System:
##   User input: Argentina_GKBsAs 
##   wkt:
## PROJCRS["Argentina_GKBsAs",
##     BASEGEOGCRS["Campo Inchauspe",
##         DATUM["Campo Inchauspe",
##             ELLIPSOID["International 1924",6378388,297,
##                 LENGTHUNIT["metre",1]],
##             ID["EPSG",6221]],
##         PRIMEM["Greenwich",0,
##             ANGLEUNIT["Degree",0.0174532925199433]]],
##     CONVERSION["unnamed",
##         METHOD["Transverse Mercator",
##             ID["EPSG",9807]],
##         PARAMETER["Latitude of natural origin",-34.6297166,
##             ANGLEUNIT["Degree",0.0174532925199433],
##             ID["EPSG",8801]],
##         PARAMETER["Longitude of natural origin",-58.4627,
##             ANGLEUNIT["Degree",0.0174532925199433],
##             ID["EPSG",8802]],
##         PARAMETER["Scale factor at natural origin",0.999998,
##             SCALEUNIT["unity",1],
##             ID["EPSG",8805]],
##         PARAMETER["False easting",100000,
##             LENGTHUNIT["metre",1],
##             ID["EPSG",8806]],
##         PARAMETER["False northing",100000,
##             LENGTHUNIT["metre",1],
##             ID["EPSG",8807]]],
##     CS[Cartesian,2],
##         AXIS["(E)",east,
##             ORDER[1],
##             LENGTHUNIT["metre",1,
##                 ID["EPSG",9001]]],
##         AXIS["(N)",north,
##             ORDER[2],
##             LENGTHUNIT["metre",1,
##                 ID["EPSG",9001]]]]

#Si hay que descargar archivo, hay que cambiar el txt!! cuando lo guardas(hacerlo como guardar como) poner gjson

#Tomar alojamientos desde el csv de usos del suelo

usosdelsuelo_hoteles <- read_delim("https://cdn.buenosaires.gob.ar/datosabiertos/datasets/relevamiento-usos-del-suelo/relevamiento-usos-del-suelo-2017.csv",delim = ",") %>% 
  filter(TIPO2_16  =="HOTEL"| TIPO2_16 =="HOTEL FAMILIAR")
## Parsed with column specification:
## cols(
##   X = col_double(),
##   Y = col_double(),
##   SMP = col_character(),
##   CALLE = col_character(),
##   NUM = col_double(),
##   TIPO1_16 = col_character(),
##   TIPO2_16 = col_character(),
##   PISOS_16 = col_double(),
##   NOMBRE = col_character(),
##   OBSERVACIO = col_character(),
##   BARRIO = col_character(),
##   COMUNA = col_double(),
##   `5_DIG` = col_character(),
##   `4_DIG` = col_character(),
##   `3_DIG` = col_character(),
##   `2_DIG` = col_character(),
##   RAMA = col_character(),
##   SUBRAMA = col_character(),
##   SSRAMA = col_character()
## )
usosdelsuelo_hoteles <- st_as_sf(usosdelsuelo_hoteles,coords=c("X","Y"), crs=4326)
usosdelsuelo_hoteles<- st_transform(usosdelsuelo_hoteles, crs="+proj=tmerc +lat_0=-34.6297166 +lon_0=-58.4627 +k=1 +x_0=100000 +y_0=100000 +ellps=intl +units=m +no_defs")
coberturaalojamientos <- st_buffer(usosdelsuelo_hoteles,dist = 1000)
coberturaalojamientos <- coberturaalojamientos %>% summarise(cobertura=TRUE) 
coberturaalojamientos <- coberturaalojamientos%>% 
  st_transform(4326)

#Cargamos el csv de properati

properati <- read.csv("D:/Documents/01-Ditella/Instrumentos de Analisis Urbano II/segunda etapa/rent_properati_2020_2021.csv",stringsAsFactors = FALSE,  encoding="bytes")
sapply(properati, class)
##         ad_type      start_date        end_date      created_on             lat 
##     "character"     "character"     "character"     "character"       "numeric" 
##             lon              l1              l2              l3              l4 
##       "numeric"     "character"     "character"     "character"     "character" 
##              l5              l6           rooms        bedrooms       bathrooms 
##     "character"       "logical"       "integer"       "integer"       "integer" 
##   surface_total surface_covered           price        currency    price_period 
##       "integer"       "integer"       "integer"     "character"     "character" 
##   property_type  operation_type 
##     "character"     "character"

#Cargamos filtramos departamentos y obtenemos el precio/m2 de cada uno. Utilizamos moneda Argentina

properati <- properati%>% 
  filter(operation_type =="Alquiler") %>% 
  filter(lat !="") %>% 
    filter(lon !="") %>% 
  filter(l2== "Capital Federal") %>% 
    filter(l3 !="") %>% 
  filter(currency == "ARS") %>% 
  filter(property_type== "Departamento") %>% 
  filter(price!="") %>% 
  mutate(precioxm2=(price/surface_total)) %>% 
filter(precioxm2!="")
properatipromedio <- properati %>% 
     group_by(l3) %>% 
  summarise(precioxm2 = mean(precioxm2)) %>% 
rename("BARRIO"="l3")
## `summarise()` ungrouping output (override with `.groups` argument)
  head(properatipromedio)
## # A tibble: 6 x 2
##   BARRIO       precioxm2
##   <chr>            <dbl>
## 1 Abasto            511.
## 2 Agronomía       486.
## 3 Almagro           528.
## 4 Balvanera         491.
## 5 Barracas          467.
## 6 Barrio Norte      577.
properatipromedio <- data.frame(lapply(properatipromedio, function(v) {
  if (is.character(v)) return(toupper(v))
  else return(v)
}))

#Damos el valor de precioxm2 a cada hotel

alojamientosconprecio <- left_join(usosdelsuelo_hoteles, properatipromedio, by = "BARRIO") 
head(alojamientosconprecio)
## Simple feature collection with 6 features and 18 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: 100834.4 ymin: 104264.2 xmax: 101567.4 ymax: 105403.1
## CRS:            +proj=tmerc +lat_0=-34.6297166 +lon_0=-58.4627 +k=1 +x_0=100000 +y_0=100000 +ellps=intl +units=m +no_defs
## # A tibble: 6 x 19
##   SMP   CALLE   NUM TIPO1_16 TIPO2_16 PISOS_16 NOMBRE OBSERVACIO BARRIO COMUNA
##   <chr> <chr> <dbl> <chr>    <chr>       <dbl> <chr>  <chr>      <chr>   <dbl>
## 1 049-~ OLLE~  4186 EDU      HOTEL          11 <NA>   <NA>       CHACA~     15
## 2 033-~ FITZ~   774 EDU      HOTEL           2 <NA>   <NA>       CHACA~     15
## 3 033-~ CORD~  6372 EDU      HOTEL           3 <NA>   <NA>       CHACA~     15
## 4 033-~ ALVA~   318 EDU      HOTEL           1 <NA>   <NA>       CHACA~     15
## 5 033-~ MAURE  3532 EDU      HOTEL           3 <NA>   <NA>       CHACA~     15
## 6 037-~ GARC~  3570 EDU      HOTEL           1 <NA>   <NA>       CHACA~     15
## # ... with 9 more variables: `5_DIG` <chr>, `4_DIG` <chr>, `3_DIG` <chr>,
## #   `2_DIG` <chr>, RAMA <chr>, SUBRAMA <chr>, SSRAMA <chr>, geometry <POINT
## #   [m]>, precioxm2 <dbl>

#Vamos a aplicar la accesibilidad a nuestro dataset

manzanas <- read_sf("D:/Documents/01-Ditella/Instrumentos de Analisis Urbano II/manzanas.geojson")
avenidas <- calles %>% filter(tipo_c == "AVENIDA")
plot(avenidas[,c("sentido")])

manzanas <- st_transform(manzanas,crs = st_crs(usosdelsuelo_hoteles))
manzanasCentroides <- st_centroid(manzanas)
## Warning in st_centroid.sf(manzanas): st_centroid assumes attributes are constant
## over geometries of x
ggplot() +
  geom_sf(data = manzanas) +
  geom_sf(data = manzanasCentroides,color="red", size= 0.001)

avenidas <- st_transform(avenidas,crs = st_crs(usosdelsuelo_hoteles))
distanciaAvenidas <- st_distance(manzanasCentroides,avenidas)
# 12.520 filas (centroides de manzanas) y 6,758 columnas (tramos de avenidas)
dim(distanciaAvenidas)
## [1] 12520  6686
# 1 significa filas, 2 columnas. functon(x) min(x) significa que para cada fila devuelva el valor mínimo
avenidaMasCercana <- apply(distanciaAvenidas,1,function(x) min(x))
# Rendondeamos
avenidaMasCercana <- round(avenidaMasCercana,0)
manzanas <- manzanas %>% mutate(distanciaAvenida=avenidaMasCercana)
manzanasCentroides <- st_join(manzanasCentroides,usosdelsuelo_hoteles)
#manzanasCentroides <- manzanasCentroides %>%
#mutate(cobertura=ifelse(is.na(cobertura),TRUE,cobertura))
radiosCensales <- read_sf("D:/Documents/01-Ditella/Instrumentos de Analisis Urbano II/caba_radios_censales.geojson")
glimpse(radiosCensales)
## Rows: 3,554
## Columns: 9
## $ RADIO_ID    <chr> "1_1_1", "1_12_1", "1_12_10", "1_12_11", "1_12_2", "1_1...
## $ BARRIO      <chr> "RETIRO", "SAN NICOLAS", "SAN NICOLAS", "SAN NICOLAS", ...
## $ COMUNA      <chr> "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", ...
## $ POBLACION   <dbl> 336, 341, 296, 528, 229, 723, 393, 600, 472, 786, 329, ...
## $ VIVIENDAS   <dbl> 82, 365, 629, 375, 445, 744, 341, 505, 504, 546, 275, 8...
## $ HOGARES     <dbl> 65, 116, 101, 136, 129, 314, 209, 275, 202, 347, 129, 3...
## $ HOGARES_NBI <dbl> 19, 25, 1, 7, 16, 104, 110, 32, 49, 89, 15, 57, 1, 1, 2...
## $ AREA_KM2    <dbl> 1.79899705, 0.01856469, 0.04438025, 0.36634000, 0.01836...
## $ geometry    <MULTIPOLYGON [°]> MULTIPOLYGON (((-58.37189 -..., MULTIPOLYG...
#radiosCensales <- radiosCensales %>% mutate(densidadPob=POBLACION/AREA_KM2)
#radiosCensales <- radiosCensales %>% st_transform(radiosCensales,crs=st_crs(usosdelsuelo_hoteles))
#manzanasCentroides <- st_join(manzanasCentroides,radiosCensales)
# Elegimos solo las variables que queremos unir, antes lo convertimos en data frame para poder perder la columna geometry
#manzanasCentroides <- manzanasCentroides %>% 
                  #    as.data.frame() %>%
                   #   select(SM,densidadPob,HOGARES_NBI,cobertura)
#manzanas <-  left_join(manzanas,manzanasCentroides,by="SM")