[R] help me avoid nested for() loops!
Dylan Beaudette
debeaudette at ucdavis.edu
Fri Nov 20 23:58:56 CET 2009
?dist
On Friday 20 November 2009, 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)
>
> 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],poi
>nts[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
>
> ______________________________________________
> 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.
--
Dylan Beaudette
Soil Resource Laboratory
http://casoilresource.lawr.ucdavis.edu/
University of California at Davis
530.754.7341
More information about the R-help
mailing list