[R] summation involving multiple summations

mahmoudfarid30 at yahoo.com mahmoudfarid30 at yahoo.com
Sat Mar 19 14:17:38 CET 2016


Dear R Experts 

I've a function which involves multiple summations, and the number of summations depends on a 
random variable named (n-r), where n is known but r is random and r<n. 

So, if , for example , n-r=3, the function is: 

>n_r=3 
>fx=function(x)sum(sapply(1:n_r, function(j1) {sum(sapply(1:(j1), function(j2){sum(sapply(1:(j2), function(j3){(j1>j2)*(j2>j3)/(x+exp(tc[j1]+tc[j2]+tc[j3])^4}))}))}))} 

The value of r will be generated from a simulation process, so in one iteration r may be equal to 0, and in another iteration it might be equal to 2 and so on, and accordingly  (n-r) is either 1, 2, or 3. And this makes the body of the summation different every time. 


Here's my  trail code in the simple case when n=3: 

library(nleqslv) 
N=100;n=3 
a=matrix(0,nrow=N,ncol=1) 
for(i in 1:N){ 
tc=matrix(0, nrow=n, ncol=1) 
t=matrix(0, nrow=n, ncol=1) 
c=matrix(0,nrow=n,ncol=1) 
for(j in 1: n){ 
t[j]=rexp(1,rate=3) 

c[j]=rexp(1, rate =2) 
if (t[j]>=c[j]) {tc[j]=t[j]} 
} 
n_r=nrow(tc) 
if(n_r==1){fx=function(x)sum(sapply(1:n-3, function(j1){1/(x+exp(tc[j1]))^4})) 
a[i]=nleqslv(0.5, fx)$x 
} 
if(n_r==2){fx=function(x)sum(sapply(1:n-2, function(j1){sum(sapply(1:(j1),function(j2){(j1>j2)/(x+exp(tc[j1]+tc[j2]))^4}))})) 
a[i]=nleqslv(0.5, fx)$x 
} 
if(n_r==3){fx=function(x)sum(sapply(1:n, function(j1) {sum(sapply(1:(j1), function(j2){sum(sapply(1:(j2), 
function(j3){(j1>j2)*(j2>j3)/(x+exp(tc[j1]+tc[j2]+tc[j3]))^4}))}))})) 
a[i]=nleqslv(0.5, fx)$x 
} 
} 

Is there any other way to write a loop that could be executed for any value of r instead of putting the if ()  statement for each single value of r , as n may take large values reaching 30, for instance. 

Any help or recommendation for a reference that can help me would be appreciated . 
Thank you
Mahmoud Farid



More information about the R-help mailing list