Created
August 14, 2013 14:58
-
-
Save mihi-tr/6231838 to your computer and use it in GitHub Desktop.
Querying the OpenSpending API with R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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