Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a double sum in R

Tags:

r

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.

like image 907
A.B. Si Avatar asked Oct 20 '22 02:10

A.B. Si


1 Answers

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.

like image 86
jlhoward Avatar answered Nov 15 '22 10:11

jlhoward