# Contract poll simulation


Find this notebook on the web at
<a class="quarto-xref" href="https://resampling-stats.github.io/latest-r/testing_counts_1.html#nte-contract_poll">Note <span>21.4</span></a>.

This R notebook generates samples of 50 simulated voters on the
assumption that only 50 percent are in favor of the contract. Then it
counts (`sum`s) the number of samples where over 29 (30 or more) of the
50 respondents said they were in favor of the contract. (That is, we use
a “one-tailed test.”) The result in the `kk` variable is the chance of a
“false positive,” that is, 30 or more people saying they favor a
contract when support for the proposal is actually split evenly down the
middle.



```{r}
# We will do 10,000 iterations.
n <- 10000

# Make an array of integers to store the "Yes" counts.
yeses <- numeric(n)

for (i in 1:n) {
    answers <- sample(c('No', 'Yes'), size=50, replace=TRUE)
    yeses[i] <- sum(answers == 'Yes')
}

# Produce a histogram of the trial results.
# Use integer bins for histogram, from 10 through 40.
hist(yeses, breaks=10:40,
     main='Number of yes votes out of 50, in null universe')
```

In the histogram above, we see that about 11 percent of our trials had
30 or more voters in favor, despite the fact that they were drawn from a
population that was split 50-50. R will calculate this proportion
directly if we add the following commands to the above:

```{r}
k <- sum(yeses >= 30)
kk <- k / n
message('Proportion >= 30: ', round(kk, 2))
```
