Skip to content

Instantly share code, notes, and snippets.

@HuangRicky
Created January 19, 2017 22:53
Show Gist options
  • Select an option

  • Save HuangRicky/50677be562b8ef5441f2d3a7c79141da to your computer and use it in GitHub Desktop.

Select an option

Save HuangRicky/50677be562b8ef5441f2d3a7c79141da to your computer and use it in GitHub Desktop.
ACLED API Calls in R
library(httr)
library(dplyr)
ACLED_call <- function(query="") {
url <- paste0("http://acleddata.com/api/acled/read", query)
resp <- GET(url)
if (http_type(resp) != "application/json") {
stop("API did not return json", call. = FALSE)
}
rst <- jsonlite::fromJSON(content(resp, "text",encoding = 'UTF-8'), simplifyVector = FALSE)
if(!rst$success){
stop("request wasn't success")
}
rst <- rst$data
if(length(rst)==0L)return(NULL)
r <- data.frame(matrix(unlist(rst),byrow = T,nrow=length(rst)),stringsAsFactors = F)
names(r) <- names(rst[[1L]])
r
}
ACLED_load <- function(condition = "", limit = 500L, verbose = F){
iscomplete <- F
all_rst <- NULL
currenti <- 1L
while(!iscomplete){
if(verbose[1L]) cat(paste0(" *** Loading ACLED on condition: '",condition,"' with each bulk of ",limit,", round ",currenti,"..."))
q <- paste0('?',condition,ifelse(condition[1L]=='','','&'),"limit=",limit[1L],"&page=",currenti)
rst <- acled_call(q)
if(is.null(rst) || nrow(rst)<limit){
iscomplete <- T
}
currenti <- currenti + 1L
all_rst <- bind_rows(all_rst,rst)
if(verbose[1L]) cat("ok ***\n")
}
if(verbose[1L]) cat(" *** Got all ACLED data. ***\n")
all_rst %>% tbl_df
}
if(F){
a2016 <- acled_load("year=2016")
a2017 <- acled_load("year=2017")
# this will load everything, may take a while.
ACLED_all <- acled_load()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment