Skip to content

Instantly share code, notes, and snippets.

# tvladeck/Presidential Simulation.R Created Oct 1, 2012

Really really informal simulation of the election
 library("hash") # States treated as going democratic with probability 1 DemStates <- hash() .set(DemStates, "WA"=12, "OR"=7, "CA"=55, "NM"=5, "MN"=10, "WI"=10, "MI"=16, "IL"=20, "PA"=20, "MD"=10, "DC"=3, "DE"=3, "NJ"=14, "CT"=7, "RI"=4, "MA"=11, "VT"=3,"ME"=4,"HI"=4, "NY"=29) # States treated as going republican with probability 1 RepStates <- hash() .set(RepStates, "ID"=4, "UT"=6, "WY"=3, "MT"=3, "ND"=3, "SD"=3, "NE"=5, "KS"=6, "OK"=7, "TX"=38, "AZ"=11, "MO"=10, "AR"=6, "LA"=8, "MS"=6, "AL"=9, "GA"=16, "TN"=11, "KY"=8, "WV"=5, "SC"=9, "AK"=3, "IN"=11) # Swing States # First entry in each value of the hash is the electoral # college vote # Second entry is the intrade probability of the state # going democratic SwingStates <- hash() .set(SwingStates, "NV"= c(6, 0.812), "CO"=c(9, 0.762), "IA"=c(6, 0.750), "VA"=c(13, 0.741), "NC"=c(15, 0.370), "FL"=c(29, 0.678), "NH"=c(4, 0.786), "OH"=c(18, 0.779)) # electoral college votes needed to win kCountNeeded <- 538/2 Run.Simulation <- function () { # Returns TRUE if simulation predicts democratic win # ... and FALSE otherwise # treats each state as independent (I know - not true...) dem.count <- sum(values(DemStates)) for (i in keys(SwingStates)) { result <- runif(1) state <- SwingStates[[i]] if (result < state) { dem.count <- dem.count + state } } if (dem.count > kCountNeeded) { return(T) } else { return(F) } } Run.Simulations <- function(count) { # returns portion of simulations that returned a # democratic win i <- 0 total.results <- c() while (i < (count + 1)){ single.result <- Run.Simulation() total.results <- append(total.results, single.result) i <- i + 1 } return(sum(total.results)/count) } Run.Simulations(10000) #=> 0.9894
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.