Thursday, April 30, 2026

Agresti-Caffo confidence interval for the difference of two independent proportions

sample.diff.props.CI <- function(x, n)
{
    ## Purpose: Calculate the Agresti-Caffo confidence interval for the difference of two independent proportions.
    ##          It applies the "plus-four" adjustment (+1 success and +1 failure per group)
    ## 
    ## Author: Feiming Chen (Copyright 2026; GPLv3; No Warranty; gnu.org/licenses)
    ## 
    ## Arguments: 
    ##   - x : a vector of two numerators (x1, x2)
    ##   - n : a vector of two denominators (n1, n2)
    ## 
    ## Return: 
    ##   - Point estimate (raw, unadjusted): "x1 / n1 - x2 / n2"
    ##   - Agresti-Caffo (AC) 95% two-sided confidence interval
    ## ________________________________________________

    x1 <- x[1]; x2 <- x[2]
    n1 <- n[1]; n2 <- n[2]

    ## 1. Apply adjustments (add 1 success and 1 failure to each group)
    p1_tilde <- (x1 + 1) / (n1 + 2)
    p2_tilde <- (x2 + 1) / (n2 + 2)
    n1_tilde <- n1 + 2
    n2_tilde <- n2 + 2
        
    ## 2. Calculate point difference and standard error
    diff0 <- x1/n1 - x2/n2              # raw difference as point estimate
    diff <- p1_tilde - p2_tilde
    se <- sqrt((p1_tilde * (1 - p1_tilde) / n1_tilde) + (p2_tilde * (1 - p2_tilde) / n2_tilde))
    
    ## 3. Determine critical z-value (two-sided 5% type I error protection)
    z <- qnorm(0.975)
        
    ## 4. Construct Interval
    lower <- diff - z * se
    upper <- diff + z * se
 
    cat(paste0(round(diff0 * 100, 2), "%  (", round(lower*100, 2), "% , ", round(upper*100, 2), "%)\n\n"))

    ## cat("Compare: prop.test\n")         # Wald with continuity correction (too wide)
    ## prop.test(x, n)
}
if (F) {
    sample.diff.props.CI(c(10, 5), c(20, 20))  # 25%  (-5.25% , 50.71%)
    sample.diff.props.CI(c(56, 48), c(70, 80)) # 20%  (5.25% , 33.58%)
    sample.diff.props.CI(c(9, 3), c(10, 10))   # 60%  (16% , 84%)
}

No comments:

Post a Comment