Skip to content

Instantly share code, notes, and snippets.

@Protonk
Created December 11, 2010 19:05
Show Gist options
  • Save Protonk/737575 to your computer and use it in GitHub Desktop.
Save Protonk/737575 to your computer and use it in GitHub Desktop.
GDP growth and reverting toward own mean and ensemble mean
#Downloads the data
library(WDI)
growth.df<-WDI(country="all",indicator="NY.GDP.MKTP.KD.ZG",start=1961,end=2009,extra=TRUE);
growth.df<-subset(growth.df,growth.df$region != "Aggregates")
growth.df<-growth.df[,c(2:4)]
names(growth.df)<-c("country","year","growth")
growth.df$country<-as.factor(growth.df$country)
growth.df<-growth.df[which(complete.cases(growth.df)),]
#breaks data up into rows of countries and columns of years so I can apply diff() to it
growth.cast<-cast(melt(growth.df,id.vars=c("country","year")),formula=country~year)
growth.diff<-t(diff((t(growth.cast[,-1]))));
#Returns it to the original format of growth.df so I can plug it back in
country.char<-as.character(growth.cast[,1]);
growth.diff<-data.frame(country=country.char,as.matrix(growth.diff))
colnames(growth.diff)<-c("country",1962:2009);
melt.diff<-melt(growth.diff,id.vars="country");
colnames(melt.diff)<-c("country","year","diff");
#thanks to http://tolstoy.newcastle.edu.au/R/help/03a/6316.html !
melt.diff$year<-as.numeric(levels(melt.diff$year)[as.integer(melt.diff$year)]);
#Wow merging this was easy
growth.merge<-merge(growth.df,melt.diff,by.y=c("country","year"))
growth.merge$sgn<-cut(growth.merge$diff,breaks=c(-Inf,0,Inf),labels=c("Grew Less","Grew More"))
#Could probably get away with doing this only once, but that's a job for another day
growth.merge<-growth.merge[which(complete.cases(growth.merge)),];
#Builds year and country means and computes differences from own mean and from mean in a time period
growth.df<-merge(growth.df,ddply(growth.df,.(country),summarise,country.mean=mean(growth,na.rm=FALSE)),by.y="country")
growth.df<-merge(growth.df,ddply(growth.df,.(year),summarise,year.mean=mean(growth,na.rm=TRUE)),by.y="year")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment