Testing a single proportion

To test a single proportion using the infer package, we will use the gss (General Social Survey) dataset. In this example, we will test whether the proportion of college graduates in the population is equal to 30%.

The process follows the four main verbs of the infer pipeline: specify(), hypothesize(), generate(), and calculate().

The Hypothesis Test

library(infer)
library(dplyr)
set.seed(33)
# 1. Calculate the observed statistic from the data
obs_stat <- gss |>
  specify(response = college, success = "degree") |>
  calculate(stat = "prop")
obs_stat
Response: college (factor)
# A tibble: 1 × 1
   stat
  <dbl>
1 0.348
# 2. Generate the null distribution
null_distribution <- gss |>
  specify(response = college, success = "degree") |>
  hypothesize(null = "point", p = 0.30) |>
  generate(reps = 10000, type = "draw") |>
  calculate(stat = "prop")

# 3. Visualize the results
null_distribution |>
  visualize() +
  shade_p_value(obs_stat = obs_stat, direction = "two-sided")

# 4. Get the p-value
null_distribution |>
  get_p_value(obs_stat = obs_stat, direction = "two-sided")
# A tibble: 1 × 1
  p_value
    <dbl>
1   0.024

Doing a similar thing with a for loop.

set.seed(32)
D <- 10^4
phat <- numeric(D)
for(i in 1:D){
  xs <- rbinom(1, 500, 0.3)
  phat[i] <- xs/500
}
hist(phat)
abline(v = c(.3 - .048, .3 + .048), col = "blue")

(pvalue <- mean(phat >= obs_stat$stat)*2)
[1] 0.0236
# Or
mean(phat >= .348) + mean(phat <= 0.3 -.048)
[1] 0.0216
xtabs(~college, data = gss) -> T1
T1
college
no degree    degree 
      326       174 
prop.table(T1)
college
no degree    degree 
    0.652     0.348 
prop.test(x = 174, n = 500, p = 0.3, alternative = "two.sided")

    1-sample proportions test with continuity correction

data:  174 out of 500, null probability 0.3
X-squared = 5.2595, df = 1, p-value = 0.02183
alternative hypothesis: true p is not equal to 0.3
95 percent confidence interval:
 0.3065857 0.3917874
sample estimates:
    p 
0.348 
# Or
binom.test(x = 174, n = 500, p = 0.3, alternative = "two.sided")

    Exact binomial test

data:  174 and 500
number of successes = 174, number of trials = 500, p-value = 0.02172
alternative hypothesis: true probability of success is not equal to 0.3
95 percent confidence interval:
 0.3062541 0.3915556
sample estimates:
probability of success 
                 0.348