Reputation: 2389
Say I have a binomial.coeff function defined as:
combn <- function(n,r) {
factorial(n)/(factorial(r)*factorial(n-r))
}
binomial.coeff <- function(n,x,p) {
combn(n,x)*p^x*(1-p)^(n-x)
}
I would like to call the function binomial.coeff
for different values of x
and sum the calls to produce the result. I'm not sure if R
takes many positional arguments like this:
binomial.coeff <- function(n,...,p) {
combn(n,...)*p^...*(1-p)^(n-...)
}
My final goal is say x
takes values [3,2]
then I would like to have the function being summed on 3 and 2
binomial.coeff <- function(n,x,p) {
combn(n,3)*p^3*(1-p)^(n-3)+combn(n,2)*p^2*(1-p)^(n-2)
}
Upvotes: 0
Views: 211
Reputation: 206466
Since you are using functions that are themselves vectorized, you can pass in a vector for x
with
binomial.coeff(3,2:3,.25)
# [1] 0.140625 0.015625
and sum that with
sum(binomial.coeff(3,2:3,.25))
# [1] 0.15625
More generally, if you want to call it multiple times with different parameter values, in R you'd use something like sapply
. For example
sapply(2:3, function(x) binomial.coeff(3, x, .25))
# [1] 0.140625 0.015625
sum(sapply(2:3, function(x) binomial.coeff(3, x, .25)))
# [1] 0.15625
But the code you've written seems to be the pmf for the binomial distribution. There is a built in function for that dbinom
You could do the same thing with
dbinom(2:3, 3, .25)
# [1] 0.140625 0.015625
sum(dbinom(2:3, 3, .25))
# [1] 0.15625
in one call because dbinom
is vectorized over the x
argument. Also this version would be more efficient.
Upvotes: 2