Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Created September 20, 2010 18:10
Show Gist options
  • Save ramnathv/588339 to your computer and use it in GitHub Desktop.
Save ramnathv/588339 to your computer and use it in GitHub Desktop.
# load libraries
library(ggplot2);
library(Zelig);
# function to extract coefficients of a zelig model
sd.coef2 = function(x){
est = summary(x)$coef[,1];
se = summary(x)$coef[,2];
var = names(est);
ci.lo1 = est - se*1;
ci.hi1 = est + se*1;
ci.lo2 = est - se*2;
ci.hi2 = est + se*2;
tmp = as.character(formula(x));
model = paste(tmp[2], tmp[3], sep = " ~ ");
return(data.frame(model, var, est, se, ci.lo1, ci.hi1, ci.lo2, ci.hi2))
}
## run zelig models, create a list, and use plyr to assemble data frame of model components
m1 <- zelig(GNP ~ Unemployed, data = longley, model = "ls")
m2 <- zelig(GNP ~ Armed.Forces, data = longley, model = "ls")
m3 <- zelig(GNP ~ Population, data = longley, model = "ls")
m4 <- zelig(GNP ~ Unemployed + Armed.Forces, data = longley, model = "ls")
m5 <- zelig(GNP ~ Armed.Forces + Population, data = longley, model = "ls")
m6 <- zelig(GNP ~ Unemployed + Armed.Forces + Population, data = longley,
model = "ls");
ml = list(m1, m2, m3, m4, m5, m6);
df = ldply(ml, sd.coef2);
# plot regression coefficients
plot1 = ggplot(df, aes(x = model, y = est)) +
geom_pointrange(aes(ymin = ci.lo1, ymax = ci.hi1)) +
facet_grid(var ~ ., scales = 'free_y') +
theme_bw() +
opts(axis.text.x = theme_text(angle = 45, hjust = 1, size = 8));
## TODO: figure out how to set the scales free in this plot
plot2 = ggplot(df, aes(x = model, y = est)) +
geom_pointrange(aes(ymin = ci.lo1, ymax = ci.hi1)) +
coord_flip() +
facet_grid(. ~ var, scales = 'free') +
theme_bw();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment