(1) Run following function (comtrade api for R) once. COMTRADE data can be manually, but with limited flexibility at http://comtrade.un.org/data/
get.Comtrade <- function(url="http://comtrade.un.org/api/get?"
,maxrec=50000
,type="C"
,freq="A"
,px="HS"
,ps="now"
,r
,p
,rg="all"
,cc="TOTAL"
,fmt="json"
)
{
string<- paste(url
,"max=",maxrec,"&" #maximum no. of records returned
,"type=",type,"&" #type of trade (c=commodities)
,"freq=",freq,"&" #frequency
,"px=",px,"&" #classification
,"ps=",ps,"&" #time period
,"r=",r,"&" #reporting area
,"p=",p,"&" #partner country
,"rg=",rg,"&" #trade flow
,"cc=",cc,"&" #classification code
,"fmt=",fmt #Format
,sep = ""
)
if(fmt == "csv") {
raw.data<- read.csv(string,header=TRUE)
return(list(validation=NULL, data=raw.data))
} else {
if(fmt == "json" ) {
raw.data<- fromJSON(file=string)
data<- raw.data$dataset
validation<- unlist(raw.data$validation, recursive=TRUE)
ndata<- NULL
if(length(data)> 0) {
var.names<- names(data[[1]])
data<- as.data.frame(t( sapply(data,rbind)))
ndata<- NULL
for(i in 1:ncol(data)){
data[sapply(data[,i],is.null),i]<- NA
ndata<- cbind(ndata, unlist(data[,i]))
}
ndata<- as.data.frame(ndata)
colnames(ndata)<- var.names
}
return(list(validation=validation,data =ndata))
}
}
}
(2) Run following function to download annual rice export value of Cambodia (aggregated from all other reporters) between 1990 and 2014 (116 is country code for Cambodia, and 1006 is commodity code of rice)
dat <- 1990:2014
dat <- as.data.frame(dat,ncol=1)
colnames(dat) <- "year"
dat$rice_x <- NA
for(i in 1990:2014){
tmp <- NA
tmp <- get.Comtrade(r="all", p="116",ps=i, px="H0", cc="1006", rg=1,fmt="csv")
dat$rice_x[dat$year==i] <- sum(tmp$data$Trade.Value..US..,na.rm=TRUE)
print(dat[dat$year==i,])
Sys.sleep(1)
}
(3) Run following code to save below graph in tif format
tiff(file="cambodia_rice_export.tif",width=6,height=6, unit="in",res=300)
plot(dat$year,dat$rice_x/1000000,ylab="Million USD",xlab="Year",type="o",col="blue")
dev.off()