0

`There exists r such that: \sum_{i=r}^{n}{\left(\frac{n!}{i!(n-i)!}\right)\left(\pi_0^i\right){(1-\pi_0)}^{\left(n-i\right)}\le\alpha} \sum_{i=r}^{n}{\left(\frac{n!}{i!(n-i)!}\right)\left(\pi_1^i\right){(1-\pi_1)}^{\left(n-i\right)}\geq\left(1-\beta\right)}

write a basic R function to find the sample size using the exact test for this scenario: {(\pi}_0,\pi_1)=(0.23,0.36),(\alpha,\beta)=(0.05,0.15) What is the minimum sample size? `

I use the following code:

sample_size <- function(pi0, pi1, alpha, beta) {
  n <- 1 # set a high initial value for n
  r <- 0 # set an initial value for r
  
  while (TRUE) {
    sum1 <- 0
    sum2 <- 0
    for (i in r:n) {
      sum1 <- sum1 + factorial(n)/(factorial(i)*factorial(n-i))*pi0^i*(1-pi0)^(n-i)
      sum2 <- sum2 + factorial(n)/(factorial(i)*factorial(n-i))*pi1^i*(1-pi1)^(n-i)
    }
    if (sum1 <= alpha && sum2 >= 1 - beta) {
      return(n)
    } else {
      n <- n + 1
    }
    if (n >= 1e6) {
      return(NA) # return NA if sample size is too large
    }
  }
}
sample_size(pi0 = 0.23, pi1 = 0.36, alpha = 0.05, beta = 0.15)

but getting an error:

Error in if (sum1 <= alpha && sum2 >= 1 - beta) { : missing value where TRUE/FALSE needed

  • 1
    This is a _frequent_ question on SO, https://stackoverflow.com/q/7355187/3358272. You should likely learn how to debug code; as a starter, I suggest you insert `cond <- sum1 <= alpha && sum2 >= 1 - beta; if (length(cond) != 1 || anyNA(cond)) browser();` before your `if` statement and then figure out which of the parameters caused the unexpected value. – r2evans Mar 24 '23 at 19:58
  • ... namely, when `i` is 171, both `sum1` and `sum2` resolve to `NaN`, perhaps because `factorial(n)` and `factorial(i)` are both `Inf`. – r2evans Mar 24 '23 at 20:00
  • For learning debugging (it can be daunting!), I suggest https://adv-r.hadley.nz/debugging.html#browser as a good reference. – r2evans Mar 24 '23 at 21:26

0 Answers0