[R] Trying to avoid nested loop

S Ellison S.Ellison at LGCGroup.com
Fri Oct 4 16:13:49 CEST 2013


> 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}}



More information about the R-help mailing list