Skip to content

Instantly share code, notes, and snippets.

@jfarid27
Last active July 21, 2016 23:00
Show Gist options
  • Save jfarid27/01ce03106f651dff3660699e9a6fedcd to your computer and use it in GitHub Desktop.
Save jfarid27/01ce03106f651dff3660699e9a6fedcd to your computer and use it in GitHub Desktop.
Simulates outcomes of electoral college votes
## Trump winning distribution using RealClear politics map
# http://www.realclearpolitics.com/epolls/2016/president/2016_elections_electoral_college_map.html
TrumpVsClinton <- function(){
set.seed(23952359)
#Represents the toss-up states possible votes
#NV, AZ,IA, WI, OH, VA, NC, GA, FL, NH, PA, GA, ME2
statesVotingTossups = c( 6, 11, 6, 10, 18, 13, 15, 16, 29, 4, 20, 16, 1)
#Represents states leaning republican
#UT, TX, MO, MS, IN, SC, NE2
statesVotingLeanRepub = c(6, 38, 10, 6, 11, 9, 1)
#Represents states leaning dem
#OR, CO, NM, MN, NJ, CT, ME
statesVotingLeanDem = c(7, 9, 5, 10, 14, 7, 3)
#Expected votes are Likely and Solid
expectedClinton = 154
expectedTrump = 83
#Produces a single outcome of
computeOutcome <- function(){
#Simulate every state tossing up a win for either R or D
tossUpOutcomes <- sample(c("R", "D"), length(statesVotingTossups), replace=TRUE)
leanRepubOutcomes <- sample(c("R", "D"), length(statesVotingLeanRepub), prob=c(.9, .1), replace=TRUE)
leanDemOutcomes <- sample(c("D", "R"), length(statesVotingLeanDem), prob=c(.9, .1), replace=TRUE)
#Take the D toss up states and add their possible EC votes to the expected Clinton votes
simulatedClintonVotes <- sum(statesVotingTossups[tossUpOutcomes == "D"])
+ sum(statesVotingLeanDem[leanDemOutcomes == "D"]) + sum(statesVotingLeanRepub[leanRepubOutcomes == "D"])
+ expectedClinton
#Same with R states
simulatedTrumpVotes <- sum(statesVotingTossups[tossUpOutcomes == "R"])
+ sum(statesVotingLeanDem[leanDemOutcomes == "R"]) + sum(statesVotingLeanRepub[leanRepubOutcomes == "R"])
+ expectedTrump
if ( simulatedClintonVotes > simulatedTrumpVotes) {
return(TRUE)
}
return(FALSE)
}
simulateATrial <- function(iter=1000){
demWins <- 0
repWins <- 0
for (i in 1:iter){
if (computeOutcome()) {
demWins <- demWins + 1
} else {
repWins <- repWins + 1
}
}
return(c(demWins, repWins))
}
#Generates a list of [iter] simulations representing the number of times a candidate wins out of [trials] elections
simulate <- function(runs=1000000, iter=1000){
f = function(i){
x = simulateATrial(iter);
return(x)
}
flattened = unlist(lapply(1:iter, f))
return(flattened)
}
simulateSmall <- function(){
return(simulate(10000, 1000))
}
exports <- list(computeOutcome=computeOutcome, simulate=simulate, simulateSmall=simulateSmall)
return(exports)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment