rnorouzian
rnorouzian

Reputation: 7517

Could make only one optimize call in R?

I'm trying to find two ps for two binomial distributions with 5 successes (q) in 15 trials (s).

Question

I can find the two ps by calling optimize() twice (see below). But I was wondering if there is a way I could make a single optimize() call to get the same answers?

q = 5 ; s = 15 ; alpha = .05

f1 <- function (q, s, p, alpha) {
  abs((pbinom(q = q, s = s, p)) - alpha)
  }

CI[1] = optimize(f1, interval = c(0, 1), alpha = alpha, s = s, q = q, tol = 1e-12)[[1]] 
## 0.5774437 (answer is correct)

f2 <- function(q, s, p, alpha){
  abs((pbinom(q = q - 1, s = s, p, lower.tail = FALSE)) - alpha)
  }

CI[2] = optimize(f2, interval = c(0, 1), alpha = alpha, s = s, q = q, tol = 1e-12)[[1]]
## 0.141664 (answer is correct)

Upvotes: 0

Views: 52

Answers (1)

lmo
lmo

Reputation: 38500

You can add an additional argument to f use mapply here. With mapply, you can feed multiple arguments to a function in parallel. Here, we feed the lower.tail argument and the q argument. Note that mapply is just a convenience function and that you could get something similar with a for loop, once the additional argument is added to your function.

f <- function(q, s, p, alpha, lower.tail = TRUE){
    abs((pbinom(q = q, s = s, p, lower.tail = lower.tail)) - alpha)
}

mapply(function(q, x) optimize(f, interval = c(0, 1), alpha = alpha, s = s,
                               q = q, tol = 1e-12, lower.tail=x),
       c(q, q-1), c(TRUE, FALSE))

This return a matrix with the desired values

          [,1]        [,2]        
minimum   0.5774437   0.141664    
objective 4.32016e-09 1.626525e-10

Upvotes: 1

Related Questions