Last active
August 29, 2015 14:08
-
-
Save carlislerainey/ceeb121f2b8982237efd to your computer and use it in GitHub Desktop.
Illustrate the separation package
This file contains 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
# install packages (if necessary) | |
install.packages("devtools") | |
install.packages("arm") | |
# install separation and compactr from GitHub | |
devtools::install_github("carlislerainey/compactr") | |
devtools::install_github("carlislerainey/separation") | |
# load packages | |
library(separation) | |
library(arm) # for rescale() | |
# load and recode data | |
data(politics_and_need) | |
d <- politics_and_need | |
d$dem_governor <- 1 - d$gop_governor | |
d$st_percent_uninsured <- rescale(d$percent_uninsured) | |
# formula to use throughout | |
f <- oppose_expansion ~ dem_governor + | |
percent_favorable_aca + gop_leg + | |
st_percent_uninsured + bal2012 + | |
multiplier + percent_nonwhite + | |
percent_metro | |
# informative prior | |
prior_sims_4.5 <- rnorm(10000, 0, 4.5) | |
pppd <- calc_pppd(formula = f, | |
data = d, | |
prior_sims = prior_sims_4.5, | |
sep_var_name = "dem_governor", | |
prior_label = "Normal(0, 4.5)") | |
print(pppd) | |
plot(pppd) | |
plot(pppd, log_scale = TRUE) | |
# mcmc estimation | |
post <- sim_post_normal(f, d, sep_var = "dem_governor", | |
sd = 4.5, | |
n_sims = 10000, | |
n_burnin = 1000, | |
n_chains = 4) | |
print(post) | |
# compute quantities of interest | |
## dem_governor | |
X_pred_list <- set_at_median(f, d) | |
x <- c(0, 1) | |
X_pred_list$dem_governor <- x | |
qi <- calc_qi(post, X_pred_list, qi_name = "fd") | |
plot(qi, xlim = c(-1, 1), | |
xlab = "First Difference", | |
ylab = "Posterior Density", | |
main = "The Effect of Democratic Partisanship on Opposing the Expansion") | |
## st_percent_uninsured | |
X_pred_list <- set_at_median(f, d) | |
x <- seq(min(d$st_percent_uninsured), | |
max(d$st_percent_uninsured), | |
by = 0.1) | |
X_pred_list$st_percent_uninsured <- x | |
qi <- calc_qi(post, X_pred_list, qi_name = "pr") | |
plot(qi, x, | |
xlab = "Percent Uninsured (Std.)", | |
ylab = "Predicted Probability", | |
main = "The Probability of Opposition as the Percent Uninsured (Std.) Varies") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment