Skip to content

Instantly share code, notes, and snippets.

@mihi-tr
Created August 14, 2013 14:58
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 mihi-tr/6231838 to your computer and use it in GitHub Desktop.
Save mihi-tr/6231838 to your computer and use it in GitHub Desktop.
Querying the OpenSpending API with R
require(RCurl)
require(rjson)
topsuppl<-function (dataset,drilldown,year,q=c(0.75,0.9,0.99,0.999)) {
url=paste("http://openspending.org/api/2/aggregate?dataset=",dataset,"&cut=time.year:",year,"&drilldown
=",drilldown,sep="")
j=getURL(url)
data=fromJSON(j)
amounts<-as.vector(sapply(data$drilldown,function(x) { return (x$amount[[1]]) }))
labels<-as.vector(sapply(data$drilldown,function(x) { return (x$to$label) }))
a1<-amounts[labels!="(Empty)"] #Filter out empty
top1<-quantile(a1,q)
percent<-sapply(top1,function(x) {sum(a1[a1>=x])/sum(amounts)*100})
names(percent)<-(1-q)*100
return(percent)
}
# get all years
# ay<-lapply((2009:2012),function(x) {return(topsuppl("ukgov-25k-spending","to",x))})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment