# Homeruns and strikeout correlation


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_correlation_solution">Note <span>A.8</span></a>.

Solution for exercise on relationship of home runs and strikeouts, using
correlation coefficient.

```{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 correlation approach.
actual_r <- cor(homeruns, strikeout)

n_trials <- 10000
results <- numeric(n_trials)

for (i in 1:n_trials) {
    shuffled_runs <- sample(homeruns)
    fake_r <- cor(shuffled_runs, strikeout)
    results[i] <- fake_r
}

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

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

message('p shuffled r >= actual: ', round(kk, 3))
```

Interpretation: a correlation coefficient as high as the observed value
(.62) occurred only about 0.3% of the time by chance. Hence,
provisionally, we choose to reject chance as an explanation for such a
high value of the correlation coefficient.

Notice, we get the same answer for correlation coefficients as we do for
sum of products. In fact, correlation coefficients must give us the same
answer (apart from random variation from the permutation), as the tests
of association are equivalent when we compare between different
orderings of the same sequences.
