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%) }
Thursday, April 30, 2026
Agresti-Caffo confidence interval for the difference of two independent proportions
Friday, April 24, 2026
Calculate Concordance Correlation Coefficient (CCC)
CCC <- function(x, y) { ## Purpose: ## Calculate Concordance Correlation Coefficient (CCC). ## Evaluate agreement in a unitless way: CCC is between -1 and 1, with perfect (reverse) agreement at 1 (-1). ## Ref: (Page 258-289) Lawrence, I., and Kuei Lin. "A concordance correlation coefficient to evaluate reproducibility." Biometrics (1989): 255-268. ## ## Author: Feiming Chen (Copyright 2026; GPLv3; No Warranty; gnu.org/licenses) ## ## Arguments: ## - x : a numeric vector ## - y : a numeric vector (equal length as "x"; not checked) ## ## Return: ## - CCC : Concordance Correlation Coefficient (for a paired sample) ## ________________________________________________ CCC <- 2 * cov(x, y) / (var(x) + var(y) + (mean(x) - mean(y))^2) CCC } if (F) { # Unit Test CCC(1:10, 1:10) # 1 CCC(1:10, 10:1) # -1 CCC(1:10, rep(1, 10)) # 0 CCC(1:10, 11:20) # 0.15493 }
Subscribe to:
Posts (Atom)