Skip to content

Instantly share code, notes, and snippets.

@jlopezper
Last active July 25, 2018 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlopezper/30aaf279dfc4b3737939b4e39d1156d2 to your computer and use it in GitHub Desktop.
Save jlopezper/30aaf279dfc4b3737939b4e39d1156d2 to your computer and use it in GitHub Desktop.
Using CKANR API with OpenDataBCN
# Load libraries
library(ckanr)
library(XML)
library(ggmap)
library(dplyr)
# API Setup
ckanr_setup(url = "http://opendata-ajuntament.barcelona.cat/data")
# Get package list and just select the libraries visits
x <- package_list(as = "table", limit = NULL)
x <- package_show("visites-biblioteques")
#### DEPRECATED
#url <- x$resources[[1]]$url
#temp <- tempfile(fileext=".csv")
#download.file(url, temp)
#df <- readr::read_csv(temp)
#temp <- download.file(, tempfile(fileext=".csv"))
#df <- readr::read_csv(paste0(x$resources[[2]]$url, "/", "biblioteques-visites.csv"))
####
# Parse and convert xml to data frame
df <- xmlParse(GET(x$resources[[1]]$url)) %>%
xmlToDataFrame(stringsAsFactors = F)
# Some changes: convert numeric variables into it
df[,c("Latitud", "Longitud", "Visites")] <- map_df(df[,c("Latitud", "Longitud", "Visites")], as.numeric)
# Mutate in order to get a cathegorical variable
df <- as_tibble(df) %>%
mutate(Visites_cat = cut(as.numeric(Visites), breaks = c(-Inf, 50000, 120000, 300000, Inf),
labels = c("[0 - 50000]", "(50000 - 120000]", "(120000 - 300000]", " > 300000")))
# Barcelona map and plot
bcnMap <- qmap("barcelona", color = "bw", zoom = 13)
(p <- bcnMap +
geom_point(aes(x = as.numeric(Longitud), y = as.numeric(Latitud), colour = Visites_cat, size = Visites_cat),
data = df))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment