[R] nested for() loops for returning a nearest point

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Jul 30 18:58:55 CEST 2003


"Steve Sullivan" <ssullivan at qedgroupllc.com> writes:

> neighbor.id <- vector(length=length(D1$lat))
> dist.geo <- vector(length=length(D2$lat))
> for(i in 1:length(neighbor.id)){
> for(j in 1:length(dist.geo)){
> dist.geo[j] <- D1$lat[i]-D2$lat[j]}  
> 
> # Yes, I know that isn't the right formula, this is just a test
> 
> neighbor.id[i] <- D2$point.id[which.min(dist.geo)]}
> 
>  
> 
> What I get is a neighbor.id of the appropriate length, but which
> consists only of the same value repeated.  Should I instead pass the
> which.min(dist.geo) to a variable before exiting the inner (j) loop, and
> reference that variable in place of which.min(dist.geo) in the last
> line?  Or is this whole approach wrongheaded?

Wouldn't you want to define dist.geo with an abs() ? Otherwise, the
North Pole might have the largest negative difference every time...

Apart from that, things look sane to me (but the heat is killing me
today...). You can vectorize things as in 

dist.geo <- abs(D1$lat[i]-D2$lat)

and get rid of the inner loop, but the basic idea looks correct.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list