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

Andrew Barr wabarr at gmail.com
Fri Nov 20 23:05:24 CET 2009


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)

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.

Any thoughts on how to do this without for loops? I apologize in
advance if there is an obvious way around this.

Thanks!

Andrew Barr
University of Texas at Austin




More information about the R-help mailing list