Vamos a usar el API del Portal de Datos Abiertos de Lima Metropolitana.
Primero: Definimos un par de funciones que podamos reusar
# Pasamos el URL de API endpoint, y la API developer key
# por defecto sólo retorna los datos, sin metadata
get_data <- function (api_url, api_key, include_metadata=FALSE) {
api_data <- fromJSON(paste0(api_url, "?auth_key=", api_key))
data <- extract_dataframe(api_data)
if (include_metadata==FALSE) {
return(data)
} else {
metadata <- api_data[c("id", "title", "description", "user",
"tags", "created_at", "source", "link")]
metadata["timestamp"] <- as.Date(api_data$result$fTimestamp,
origin = "1970-01-01")
return(list(metadata=metadata, data=data))
}
}
# Hace el trabajo de convertir los datos de un formato secuencial
# a una data.frame de R
extract_dataframe <- function(api_data) {
header <- subset(api_data$result$fArray, fHeader==TRUE)$fStr
values <- subset(api_data$result$fArray, is.na(fHeader))$fStr
header_len <- api_data$result$fCols
df <- as.data.frame(
matrix(values,
ncol=header_len,
byrow = TRUE),
stringsAsFactors=FALSE)
colnames(df) <- header
return(df)
}
Segundo: Conseguimos los datos de la geolocalización de los paraderos del corredor TGA troncal en Lima.
# cargando las librerías necesarias
require(jsonlite, quietly=TRUE)
source("api_key.R")
# formato: api_key <- "YOUR API KEY"
api_url <- "http://api.lima.datosabiertos.pe/datastreams/invoke/PARAD-GEO-REFER-DE-LA"
troncal_fulldata <- get_data(api_url, api_key, TRUE)
troncal <- troncal_fulldata$data
Tecero: Ahora los datos de las rutas alimentadoras
api_url <- "http://api.lima.datosabiertos.pe/datastreams/invoke/PARAD-GEO-REFER-DEL-69193"
alimentadora_fulldata <- get_data(api_url, api_key, TRUE)
alimentadora <- alimentadora_fulldata$data
Cuarto: Combinamos las dos data frames y ajustamos los tipos de algunas columnas
stops <- rbind(troncal,alimentadora)
# corregir los tipos de datos de algunas columnas
stops$LONGITUD <- as.numeric(stops$LONGITUD)
stops$LATITUD <- as.numeric(stops$LATITUD)
stops$CORREDOR <- as.factor(stops$CORREDOR)
stops$TAP <- as.factor(stops$TAP)
Usamos el paquete ggmap para generar un mapa estático (formato PNG).
require(ggmap, quietly=TRUE)
# usamos el tipo "toner" de stamen
lima_tga <- get_map(c(lon=mean(stops$LONGITUD), lat=mean(stops$LATITUD)),
source="stamen", maptype="toner", zoom=12)
tga_map <- ggmap(lima_tga, extent="device")
tga_map + geom_point(data=stops, size=2,
aes(x=LONGITUD, y=LATITUD, col=TAP))
Y usando el paquete googleVis, incrustamos un mapa interactivo usando el API de Google Maps.
require(googleVis, quietly=TRUE)
rutas <- as.character(stops$TAP)
d2 <- data.frame("latlong"=paste(stops$LATITUD, stops$LONGITUD, sep=":"),
"tip" = paste(paste0("<b>Corredor: TGA - Ruta: ",
rutas, "</b>"),
stops$NOMBRE, sep="<br/>"))
tga_map2 <- gvisMap(d2, locationvar="latlong", tipvar="tip",
options=list(
showTip=TRUE,
enableScrollWheel=TRUE,
mapType='normal',
zoomLevel=19,
useMapTypeControl=TRUE,
width=900, height=900))
print(tga_map2, "chart")
sessionInfo()
## R version 3.1.1 (2014-07-10)
## Platform: x86_64-pc-linux-gnu (64-bit)
##
## locale:
## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
## [9] LC_ADDRESS=C LC_TELEPHONE=C
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] googleVis_0.5.2 mapproj_1.2-1 maps_2.3-2 ggmap_2.3
## [5] ggplot2_1.0.0 jsonlite_0.9.8
##
## loaded via a namespace (and not attached):
## [1] colorspace_1.2-2 digest_0.6.4 evaluate_0.5.5
## [4] formatR_0.10 grid_3.1.1 gtable_0.1.2
## [7] htmltools_0.2.4 httr_0.3 knitr_1.6
## [10] labeling_0.2 MASS_7.3-33 munsell_0.4.2
## [13] plyr_1.8.1 png_0.1-7 proto_0.3-10
## [16] Rcpp_0.11.2 RCurl_1.95-4.1 reshape2_1.4
## [19] RgoogleMaps_1.2.0.6 rjson_0.2.14 RJSONIO_1.2-0.2
## [22] rmarkdown_0.2.64 scales_0.2.4 stringr_0.6.2
## [25] tools_3.1.1 yaml_2.1.13