[R] help me avoid nested for() loops!

David Winsemius dwinsemius at comcast.net
Sat Nov 21 00:03:14 CET 2009


On Nov 20, 2009, at 5:05 PM, Andrew Barr wrote:

> Hi R folks,
>
> I have a massive array (object name "points") in the following form
>
>     [,1]     [,2]
> [1,] 1369   22
> [2,] 1370   22
> [3,] 1368   23
> [4,] 1369   23
> [5,] 1370   23
> [6,] 1371   23
> (10080 rows truncated)

mtx <- matrix(scan(textConnection("1369   22
  1370   22
  1368   23
  1369   23
  1370   23
  1371   23")), ncol=2, byrow=TRUE)

 > dist(mtx)
          1        2        3        4        5
2 1.000000
3 1.414214 2.236068
4 1.000000 1.414214 1.000000
5 1.414214 1.000000 2.000000 1.000000
6 2.236068 1.414214 3.000000 2.000000 1.000000

>
> These represent pixel coordinates of interest in a jpeg image.  I need
> to find the distance from each point to all other points of interest.
> The only way I can see to do this is by pythagoras and nested for
> loops.
>
> distance<-function(x1,y1,x2,y2){sqrt((x2-x1)^2 + (y2-y1)^2)}  
> #pythagoras
> for(i in 1:nrow(points)){
> 	for(j in 1:nrow(points)){
> 	dist<-c(dist,distance(points[i,1],point.array.indices[i,2],points[j, 
> 1],points[j,2]))
> }
> }
>
> This is obviously prohibitively slow with >10000 rows in the array.

I'm not sure that your request to make this fast is reasonable. The  
size of the resulting matrix will be more than most Windows machines  
will support.

>
> Any thoughts on how to do this without for loops?

I can do that operation in 8 characters ... but ...

> I apologize in
> advance if there is an obvious way around this.

I think you should be thinking about apologizing for expecting a  
relaxation of the laws of combinatorics and geometry.


>
> Thanks!
>
> Andrew Barr
> University of Texas at Austin
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list