Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster alternative to stats:binom.test #164

Open
adamkucharski opened this issue Sep 25, 2024 · 1 comment
Open

Faster alternative to stats:binom.test #164

adamkucharski opened this issue Sep 25, 2024 · 1 comment

Comments

@adamkucharski
Copy link
Member

We're currently using stats::binom.test to generate uncertainty in estimates (i.e. 95% CI using Clopper-Pearson method). For most use cases the slowdown will be limited, but this could be made much faster for longer time series estimation (e.g. cfr_time_varying()).

For example, we could switch to Wilson method:

binom_wilson <- function(x, n, conf.level = 0.95) {
  p_hat <- x / n
  z <- qnorm(1 - (1 - conf.level) / 2)
  denom <- 1 + z^2 / n
  center <- (p_hat + z^2 / (2 * n)) / denom
  half_width <- z * sqrt((p_hat * (1 - p_hat) + z^2 / (4 * n)) / n) / denom
  lower <- center - half_width
  upper <- center + half_width
  
  # Ensure boundaries within [0,1]
  lower <- max(0, lower)
  upper <- min(1, upper)
  
  list(estimate = p_hat, conf.int = c(lower, upper))
}

# Example usage
binom_wilson(50, 100)
@sbfnk
Copy link
Contributor

sbfnk commented Sep 26, 2024

Just noting that this and several other methods are available in the binom R package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants