# Bayesian analysis of Covid test result


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

You get a Covid test, and the test is negative. Now, you would like to
know what the chance is of you having Covid.

```{r}
# The number of people.
n_trials <- 1000000

# For each person, generate a True or False label,
# indicating that they have / don't have Covid.
person_has_covid <- sample(
    c(TRUE, FALSE),
    size=n_trials,
    replace=TRUE,
    prob=c(0.015, 0.985)
)

# Calculate the numbers of people with and without Covid.
n_with_covid <- sum(person_has_covid)
n_without_covid <- n_trials - n_with_covid

# In this array, we will store, for each person, whether they
# had a positive or a negative test.
test_result <- logical(n_trials)

# Draw test results for people with Covid.
test_result[person_has_covid] <- sample(
    c(TRUE, FALSE),
    size=n_with_covid,
    replace=TRUE,
    prob=c(0.6, 0.4)
)

# Draw test results for people without Covid.
# !person_has_covid` flips all Boolean values from FALSE to TRUE
# and from TRUE to FALSE.
test_result[!person_has_covid] <- sample(
    c(TRUE, FALSE),
    size=n_without_covid,
    replace=TRUE,
    prob=c(0.005, 0.995)
)

# Get the Covid statuses of all those with negative tests
# (`test_result` is a Boolean mask, like `[TRUE, FALSE, FALSE, TRUE, ...]`,
# and `!test_result` flips all Boolean values to `[FALSE, TRUE, TRUE, FALSE, ...]`.
covid_status_negative_test <- person_has_covid[!test_result]

# Now, count how many with Covid had a negative test results.
n_with_covid_and_negative_test <- sum(covid_status_negative_test)

# And how many people, overall, had negative test results.
n_with_negative_test <- length(covid_status_negative_test)

k <- n_with_covid_and_negative_test / n_with_negative_test

message('Proportion with Covid of those with negative test: ', round(k, 4))
```

This gives around 0.006 or 0.6%.
