I'm new to R, and am attempting to write a double sum function with two inputs p and q. For instance, to compute my sum on WolframAlpha, I use
Sum[p^25 * (1-q)^j * Sum[(25 choose r) * ((j-1) choose (r-1)) * ((q * (1-p)) / (p * (1 - q)))^r,{r,1,25}],{j,0,23}]
Here's an example for p = .6
and q = .5
This should be easy to write in R, but I can't figure out how to do so. (I realize that the choose function becomes choose(n,k)
, but the sums are proving intractable.)
Thanks for any help.
Here's one way:
p <- 0.6
q <- 0.5
qp <- q*(1-p)/(p*(1-q))
f <- function(r,j) choose(25,r)*choose(j-1,r-1)*qp^r
g <- function(j) p^25*(1-q)^j*sum(sapply(1:25,f,j))
sum(sapply(1:23,g))
# [1] 0.721113
You could use anonymous functions instead of f
and g
and put it all on one line, but IMO this is a little less confusing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With