[R] help me avoid nested for() loops!
Charles C. Berry
cberry at tajo.ucsd.edu
Fri Nov 20 23:36:07 CET 2009
On Fri, 20 Nov 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],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.
Apology accepted.
The obvious way is to follow the posting guide:
?distance ## suggests trying ??distance
??distance ## lists stats::dist
?dist ## Mmmmm!
HTH,
Chuck
>
> 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.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list