# Fruit fly simulation of four groups


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

This notebook uses simulation to test whether a result of 14 or more
males, or 14 or more females, can frequently arise by chance, if we look
at four groups at a time, in one trial.

A key point of the notebook here is that each trial consists of *four
groups* of 20 randomly generated hypothetical fruit flies. And if we
consider 10,000 trials, we will be examining 40,000 sets of 20 fruit
flies.

In each trial we generate 4 random samples (groups) of 20 fruit flies,
and for each, we count the number of males (“males”s) and then check
whether that group has more than 13 of either sex (actually, more than
13 “males”s or less than 7 “males”). If it does, then we change a
variable called `unusual` to 1, which informs us that for this sample,
at least 1 group of 20 fruit flies had results as unusual as the results
from the fruit flies exposed to the four treatments.

After the 10,000 runs are made, we count the number of trials where one
sample had a group of fruit flies with 14 or more of either sex, and
show the results.

```{r}
n_iters <- 10000

# Make vector to store results for each trial.
results <- numeric(n_iters)

for (i in 1:n_iters) {
    # unusual indicates whether we have obtained any trial group with more
    # than 13 of either sex. We start at 0 (= no).
    unusual <- 0
    # Repeat the following steps 4 times to constitute 4 trial groups
    # (representing treatments A, B, C, and D) of 20 flies each.
    for (j in 1:4) {
        flies <- sample(c('male', 'female'), replace=TRUE, size=20)
        n_males <- sum(flies == 'male')
        if (n_males >= 13 | n_males <= 6) {
            unusual <- 1
        }
    }
    # unusual now tells us whether we got a result as extreme as that
    # observed (unusual == 1 if we did, unusual == 0 if not). We must
    # keep track of this result in the results variable, for each experiment.
    results[i] <- unusual
}

# The number of trials for which at least one of the four tests
# exceeded 13 males or 13 females.
k <- sum(results)
kk <- k / n_iters

message('Proportion of trials with one or more group >=14 or <=6 :', kk)
```
