[R] using the apply() family to evaluate nested functions with common arguments

Maram SAlem marammagdysalem at gmail.com
Sun Oct 11 18:52:05 CEST 2015


Dear All,

I'm trying to use the apply family to evaluate 2 nested functions whose
arguments are somewhat overlapping. I'm doing this in order to evaluate
nested multiple summations in a certain equation. First, I created the s
matrix whose rows satisfy some logical condition.

n=8

m=4

D<-matrix(0,nrow=n-m+1,ncol=m-1)

for (i in 1:m-1)

 {

D[,i]<-seq(0,n-m,1)

 }

ED <- do.call(`expand.grid`,as.data.frame(D))

ED<-as.matrix(ED)

lk<-which(rowSums(ED)<=(n-m))

s<-ED[lk,]


Then, I'm trying to evaluate a function called simpfun for each row of s,
which could be easily done using the apply () function. The problem is that
within the simpfun I need to evaluate another function, incomb(). This
function has to be first evaluated for each row of the matrix LED, whose
elements are sequences having the corresponding elements of each row of s
as their upper limits.


simpfun<- function (x,n,m,p,alpha,beta)

  {

  a<-factorial(n-m)/(prod((factorial(x)))*(factorial((n-m)- sum(x))))

  b<- vector(mode = "numeric", length = m-1)

  for ( i in 1:m-1)

   {

   b[i]<- (m-i)

   }

  c<- a*((p)^(sum(x)))*((1-p)^(((m-1)*(n-m))-sum(b%*%x)))

  d <-vector(mode = "numeric", length = m-1)

   for (i in 1:m-1)

   {

   d[i]<- n- (sum(x[(1):(i)])) - i

   }

  e<- n*(prod(d))*c

  LD<-list()

   for (i in 1:(m-1))

   {

   LD[[i]]<-seq(0,x[i],1)

   }

   LD[[m]]<-seq(0,(n-m-sum(x)),1)

   LED<-expand.grid (LD)

   LED<-as.matrix(LED)

     incomb<-function(x,alpha,beta) {


g<-((-1)^(sum(LED[1,])))*(gamma((1/beta)+1))*((alpha)^(-(1/beta)))

             fd<-
choose(x[1],LED[1,1])*choose(x[2],LED[1,2])*choose(x[3],LED[1,3])

          return (g)

      }



}



where my x in the simpfun() refers to one of the rows of the s matrix, so
that I'll be able to use something like


va<-apply(s,1,simpfun,n=,m=,p=,alpha=,beta=)



to apply it to each row of s.



The problem now is that for each row of s (which is supposed to be my x in
the simpfun()) ,I need to first apply the incomb() function for all the
rows of LED.Thus, I need to modify what I wrote above in the body of the
incomb() function in terms of something like y instead of LED[1,], so that
I can again use the apply() function on all its rows first for one row of s
,say x, and then repeat this for all the other rows of s. I can't figure
out how to do this while still having the rows of s, say x, as one of the
arguments of the incomb() function for which I'm going to use the apply()
function once more.


I'm sorry if what I'm asking for is not that clear, but I'm trying to
simplfy things as much as possible so that we don't go into tedious detalis.


Thanks a lot in advance.


Maram Salem

	[[alternative HTML version deleted]]



More information about the R-help mailing list