2

OK so I have a spatial polygons data frame, and I have a point of interest. I want to add a row to the SPDF that contains the distance from the centroid of each polygon to this given point. How do I do this ?

Here is a toy dataset:

    library(sp)
    library(spdep)
    library(rgeos)

    # Create toy SPDF
    fn <- system.file("etc/shapes/eire.shp", package = "spdep")[1]
    prj <- CRS("+proj=utm +zone=30 +units=km")
    eire <- readShapeSpatial(fn, ID = "names", proj4string = prj)

    # Create a point of interest
    pt.coords <-readWKT("POINT(260 5900)")
    eire.proj<-CRS(proj4string(eire))
    proj4string(pt.coords) <- eire.proj

    # check point is on the map
    plot(eire)
    plot(pt.coords, col="Red", add=TRUE)

Ok so the SPDF data has following columns:

    > names(eire)
   [1] "A"       "towns"   "pale"    "size"    "ROADACC" "OWNCONS" "POPCHG"  "RETSALE" "INCOME"  "names"  

I want to add a extra column showing the distance from each polygon centroid to the point we defined. How do I do this ?

1 Answer 1

3

ok figured it out eventually myself

    centroid.ED <-SpatialPoints(coordinates(eire))
    proj4string(centroid.ED) <- eire.proj
    eire$distance <- gDistance(pt.coords,centroid.ED,byid=TRUE)

    > summary(eire$distance)
           1         
     Min.   : 18.44  
     1st Qu.: 56.78  
     Median : 99.48  
     Mean   :106.46  
     3rd Qu.:156.60  
     Max.   :223.84  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.