# Homeruns and strikeout sum of products.


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

Solution to exercise on relationship of home runs and strikeouts, using
sum of products.

```{r}
homeruns <- c(14, 20, 0, 38, 9, 38, 22, 31, 33,
              11, 40, 5, 15, 32, 3, 29, 5, 32)
strikeout <- c(135, 153, 120, 161, 138, 175, 126, 200, 205,
               147, 165, 124, 169, 156, 36, 98, 82, 131)
```

```{r}
# The sum of products approach.
actual_sop <- sum(homeruns * strikeout)

n_trials <- 10000
results <- numeric(n_trials)

for (i in 1:n_trials) {
    shuffled_runs <- sample(homeruns)
    fake_sop <- sum(shuffled_runs * strikeout)
    results[i] <- fake_sop
}

hist(results, breaks=25,
     main='Distribution of shuffled sum of products',
     xlab='Sum of products for shuffled homeruns')

k <- sum(results >= actual_sop)
kk <- k / n_trials

message('p shuffled sum of products >= actual: ', round(kk, 3))
```

Interpretation: In 10,000 simulations, random shuffling very rarely
produced a value as high as observed. Therefore, we conclude that random
chance could not reasonably be responsible for the observed degree of
correlation.
