public
Created

five.thirty.free

  • Download Gist
53free.r
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
library(plyr)
library(ggplot2)
library(grid)
 
 
election.data <- read.csv("http://www.oberlin.edu/faculty/cdesante/assets/downloads/election2012.csv")
five.thirty.free <- function (SIMS) {
 
Mode <- function(X) {
 
XX <- table(as.vector(X))
names(XX)[XX == max(XX)]
 
}
 
Electoral.Votes <- c()
for ( i in 1:SIMS) {
Election.Draw <- ddply(election.data,
.(STATE, OBAMA, ERROR), summarise,
P = rnorm(1, OBAMA, ERROR/1.96)
)
 
Election.Draw$Win <- ifelse(Election.Draw$P > 50 , 1, 0)
Electoral.Votes[i] <- sum(Election.Draw$Win * election.data$COLLEGE)
}
 
Winner <- ifelse(Electoral.Votes>=270, "Obama", "Romney")
P.Obama <- ifelse(Electoral.Votes>=270, 1, 0)
mean(P.Obama)
table(Winner)
Title.Text <- bquote("Probability that Obama Wins the Election:" * " " * .(round(mean(P.Obama), 3)))
Fill.Title <- c("Projected Winner: \n")
X.Title <- bquote("\n \n Electoral College Votes for Obama in" * " " * .(SIMS) * " " * "Simulations")
Plot1 <- qplot(Electoral.Votes, geom="histogram", binwidth=.5, fill=factor(Winner), alpha=mean(as.numeric(Mode(Electoral.Votes)))) + theme_bw() + scale_fill_manual(values=c("dodgerblue4", "red"))
Plot2 <- Plot1 + labs(fill = Fill.Title , title = Title.Text, alpha="Mode of Obama's \n Electoral Votes: \n") + xlab(X.Title) + ylab("Count \n")
Plot3 <- Plot2 + guides(alpha = guide_legend("Mode of Obama's \n Electoral Votes: \n",
override.aes = list(alpha = 0,
colour = "white"),
keywidth = unit(0, "cm")))
Plot3 <- Plot3 + scale_y_continuous(expand = c(0, 0))
Plot3
}
 
#Just specify the number of simulations you want to run:
 
five.thirty.free(2500)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.