Perform vectorized hypothesis tests for the difference of two proportions
Source:R/vectorized_prop_test.R
vct_prop_test_pval.RdGiven vectors x1, n1, x2 and n2, return a vector of p-values that test whether x1/n1 is the same proportion as x2/n2. All credit to David Robinson.
Examples
library(dplyr)
data("ds_newsletter")
df <-
ds_newsletter %>%
count(s_age, s_gender) %>%
group_by(s_age) %>%
mutate(sum_n = sum(n)) %>%
group_by(s_gender) %>%
mutate(overall_n = sum(n)) %>%
ungroup() %>%
mutate(overall_sum_n = sum(n))
df <-
df %>%
# vectorized p-values calculation
mutate(prop_pval1 = vct_prop_test_pval(n, sum_n, overall_n, overall_sum_n)) %>%
# rowwise calculation using prop.test
rowwise() %>%
mutate(prop_pval2 = prop.test(c(n, overall_n), c(sum_n, overall_sum_n))$p.value) %>%
ungroup()
df
#> # A tibble: 8 × 8
#> s_age s_gender n sum_n overall_n overall_sum_n prop_pval1 prop_pval2
#> <fct> <fct> <int> <int> <int> <int> <dbl> <dbl>
#> 1 18-30 Male 73 191 426 989 0.245 0.245
#> 2 18-30 Female 118 191 563 989 0.245 0.245
#> 3 31-45 Male 98 233 426 989 0.835 0.835
#> 4 31-45 Female 135 233 563 989 0.835 0.835
#> 5 46-64 Male 168 379 426 989 0.721 0.721
#> 6 46-64 Female 211 379 563 989 0.721 0.721
#> 7 65+ Male 87 186 426 989 0.394 0.394
#> 8 65+ Female 99 186 563 989 0.394 0.394