Question

I'm trying to create a combinatoric function in R and it is dependent on what number I set a variable to. This tells me I would have to use a loop. Here is an example of the equation that I am trying to create and I filled in the numbers given in the example:

The equation changes depending on what number if put in for b. I'm guessing I would need a sum and a loop.

comb = function(n, x) {return(factorial(n) / (factorial(x) * factorial(n-x)))}


a <- 8
b <- 4
c <- 0:b
p <- 0.05

total = function(n) {
  return(((comb(a,b + c)*comb((n-a), (c - b)*(-1))/comb(n,a) - 0.05)
}

I will then find out what n is equal too by setting it equal to 0.

Was it helpful?

Solution

You don't need to define comb -- this is provided by the function choose in base R. I think all you need is to combine choose and sum to compute your numerator:

total <- function(n) {
  sum(choose(a, b:(2*b)) * choose(n-a, b:0)) / choose(n, a) - p
}

# Plot total(n) for various n values:
a <- 8
b <- 4
p <- 0.05
n <- 20:100
plot(n, sapply(n, total))

enter image description here

For these parameters, total(n) crossed 0 between n=36 and n=37.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top