Thank you for your answer. This is what I needed. 

> From: s.elli...@lgcgroup.com
> To: r-help@r-project.org
> Date: Fri, 4 Oct 2013 15:13:49 +0100
> Subject: Re: [R] Trying to avoid nested loop
> 
> 
> > I'm trying to avoid using nested loops in the following code but I'm
> > not sure how to proceed. Any help would be greatly appreciated.
> > With regards,Phil
> > X = matrix(rnorm(100), 10, 10)
> > result = 0
> > for(m in 1:nrow(X)){  
> >     for(n in 1:ncol(X)){        
> >             if(X[m,n] != 0){      
> >                     result = result + (X[m,n] / (1 + abs(m - n)))    
> >             }      
> >     }
> > }
> First, you don't need  the 'if', do you? If X[m,n]==0 (rare for a floating 
> point number) (X[m,n] / (1 + abs(m - n)) will be zero anyway.
> 
> Then, depending on the matrix size, you can probably do the whole thing using 
> an index array.
> 
> Something like:
> 
> idx <- as.matrix( expand.grid(1:nrow(X), 1:ncol(X)) )
> result <- sum(  X[idx] / apply(idx,1, function(x) 1+abs(diff(x))) )
> 
> #... which seemed to do the identically the same thing as your loop when I 
> tried it.
> 
> S Ellison
> 
> 
> *******************************************************************
> This email and any attachments are confidential. Any use...{{dropped:8}}
> 
> ______________________________________________
> R-help@r-project.org mailing list
> 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]]

______________________________________________
R-help@r-project.org mailing list
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.

Reply via email to