[R] Alternatives for explicit for() loops
jim holtman
jholtman at gmail.com
Sun Nov 1 23:27:48 CET 2015
Why are you recreating the incomb function within the loop instead of
defining it outside the loop? Also you are referencing several variables
that are global (e.g., m & j); you should be passing these in as parameters
to the function.
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
On Sun, Nov 1, 2015 at 7:31 AM, Maram SAlem <marammagdysalem at gmail.com>
wrote:
> Hi All,
>
> I'm writing a long code that takes long time to execute. So I used the
> Rprof() function and found out that the function that takes about 80% of
> the time is the incomb () fucntion (below), and this is most probably
> because of the many explicit for() loops I'm using.
>
> n=18;m=4;p=0.3;alpha=0.2;beta=2
> x=c(3,0,0)
> 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)
> store1<-numeric(nrow(LED))
> h<- numeric(m-1)
> lm<- numeric(m-1)
> for (j in 1:length(store1) )
> {
> incomb<-function(x,alpha,beta) {
>
> g<-((-1)^(sum(LED[j,])))*(gamma((1/beta)+1))*((alpha)^(-(1/beta)))
> for (i in 1:(m-1)) {
> h[i]<- choose(x[i],LED[j,i])
> }
> ik<-prod(h)*choose((n-m-sum(x)),LED[j,m])
> for (i in 1:(m-1)) {
> lm[i]<-(sum(LED[j,1:i])) + i
> }
> plm<-prod(lm)
> gil<-g*ik/(plm)
> hlm<-numeric(sum(LED[j,])+(m-1))
> dsa<-length(hlm)
> for (i in 1:dsa)
> {
> ppp<- sum(LED[j,])+(m-1)
> hlm[i]<-
> (choose(ppp,i))*((-1)^(i))*((i+1)^((-1)*((1/beta)+1)))
> }
> shl<-gil*(sum(hlm)+1)
> return (shl)
> }
> store1[j]<-incomb(x,alpha=0.2,beta=2)
> }
>
>
> I'm trying to use alternatives (for ex. to vectorize things) to the
> explicit for() loops, but things don't work out.
>
> Any suggestions that can help me to speed up the execution of the incomb()
> function are much appreciated.
>
> Thanks a lot in advance.
>
> Maram Salem
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list