 rnorouzian - 3 years ago 95
R Question

# Could make only one optimize call in R?

I'm trying to find two

`p`
s for two binomial distributions with 5 successes (
`q`
) in 15 trials (
`s`
).

• For the FIRST of the two binomial distributions, I want left of "5" (i.e., 0 to 5) to have a cumulative probability of ".05" (
`alpha`
).

• For the SECOND of the two binomial distributions, I want right of "5" (i.e., 5 to 15) to have a cumulative probability of ".05"(
`alpha`
).

# Question

I can find the two
`p`
s 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 = optimize(f1, interval = c(0, 1), alpha = alpha, s = s, q = q, tol = 1e-12)[]

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

CI = optimize(f2, interval = c(0, 1), alpha = alpha, s = s, q = q, tol = 1e-12)[]
`````` lmo

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download