Skip to content
Prev 681 / 29559 Next

R function to match closest points to second point set?

On Mon, 28 Nov 2005, Rick Reeves wrote:

            
Using the Census 2000 county shapefiles for North and South Carolina as an 
example:
+ proj4string=CRS("+proj=longlat  datum=NAD83"))
+ proj4string=CRS("+proj=longlat datum=NAD83"))
+ "labpt")))
+ "labpt")))
+ dists <- spDistsN1(sc_cents, nc_cents[i,], longlat=TRUE)
+ res[i] <- which.min(dists)
+ }
+ sc_cents[res[i],1], sc_cents[res[i],2])


The results in km are in the dists matrix, the spDistsN1() function is in 
the sp package which maptools loads. Since you've got your centroids 
already, you don't need the extra stuff, so spDistsN1() in a loop will 
get you there, I needed it for the example. Add the res vector to your 
data frame.

Roger