# Simulation of Bush / Clinton polling


Find this notebook on the web at
<a class="quarto-xref" href="https://resampling-stats.github.io/edition-3-r/testing_counts_2.html#nte-bush_clinton">Note <span>23.6</span></a>.

The notebook estimates the chances that Bush is in fact equal or behind
in the population of eventual voters, despite the poll giving him a
narrow lead.

```{r}
# Number of voters who expressed a preference.
n_voters <- 705

# Benchmark proportions.
bench_ps <- c(0.35, 0.35, 0.30)

# Set the number of trials.
n_trials <- 10000

# An empty array to store the trials.
scores <- numeric(n_trials)

# Do 10000 trials
for (i in 1:n_trials) {
    # Take a sample of 705 votes, with replacement.
    samp <- sample(c('Bush', 'Perot', 'Clinton'),
                   size=n_voters,
                   prob=bench_ps,
                   replace=TRUE)
    # Count the Bush voters, etc.
    n_bush <- sum(samp == 'Bush')
    n_perot <- sum(samp == 'Perot')
    n_clinton <- sum(samp == 'Clinton')
    # Join Perot & Clinton votes into a vector.
    others <- c(n_perot, n_clinton)
    # Find the larger of the other two.
    n_second <- max(others)
    # Find Bush's margin over 2nd.
    lead <- n_bush - n_second
    # Convert vote difference to percent lead.
    pct_lead <- lead / n_voters * 100
    # Store the result.
    scores[i] <- pct_lead
}

hist(scores, breaks=50,
     main='Distribution of Bush margin over second candidate')

# Compare to the observed margin in the sample of 705 corresponding to a 6.4
# percent margin by Bush over 2nd place finisher (rounded).
k <- sum(scores >= 6.4)
kk <- k / n_trials

message('Proportion of trials where Bush margin >= 6.4%: ', kk)
```
