[R] summation involving multiple summations
Greg Snow
538280 at gmail.com
Wed Mar 23 16:15:26 CET 2016
You can create a list of functions then use subscripting. E.g.:
funvec <- c(sin, cos, tan)
for(i in 1:3) {
print(funvec[[i]](pi/6))
}
Just create the list with the different functions that you want to
call, then subscript that list with your n_r variable.
You can also look at ?switch, but I think the list of functions may
work better for you.
On Sat, Mar 19, 2016 at 7:17 AM, Mahmoud via R-help
<r-help at r-project.org> wrote:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Gregory (Greg) L. Snow Ph.D.
538280 at gmail.com
More information about the R-help
mailing list