0

I have a SpatialPolygons(DataFrame) object, e.g. SpP

library(sp)    
Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

I would like to, for each polygon, calculate the greatest distance between its centroid (coordinates(SpP)) to any other point within the same polygon (I assume this furtherest away point will be on the edge?).

Can someone show me how to do that?

qoheleth
  • 2,219
  • 3
  • 18
  • 23
  • The furthest point will always be a vertex, so compute all the centroid-vertex distances and take the max. – Spacedman Jun 05 '15 at 16:06
  • @Spacedman would you mind giving me a function? – qoheleth Jun 10 '15 at 00:45
  • Sorry, was busy when I read this and thought I'd correct your assumption about the point being on an edge. Thought that might have helped you code a solution yourself! – Spacedman Jun 10 '15 at 07:25

1 Answers1

1

Here is a simple function I created that for a given polygon calculates the centroid, and the uses basic geometry to find with point is furthest from the centroid, returning its coordinates:

library(sp)
library(rgeos)
library(ggplot2)

Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
Srs2=Polygons(list(Sr2), "s2")
spPol=SpatialPolygons(list(Srs2))

find_furthest_point=function(polygon){
  coords=fortify(polygon)[,c(1:2)]  
  center=as.data.frame(gCentroid(polygon))
  longs=coords[,1]
  lats=coords[,2]

  dist_fx=function(long, lat, center=center){
    dist=sqrt((long-center[1])^2+(lat-center[2])^2)
    return(dist)
  }
  dists=mapply(dist_fx, longs, lats, MoreArgs=list(center))
  furthest_index=as.integer(which(dists==max(dists)))
  furthest=coords[furthest_index,]  
  return(furthest)
}

find_furthest_point(Sr2)
Lucas Fortini
  • 2,420
  • 15
  • 26
  • fortify is just a way to extract data from a polygon into a dataframe – Lucas Fortini Jun 10 '15 at 01:07
  • `fortify` (for `Polygons` objects) comes from `ggplot2`, so do `library(ggplot2)` before, or edit the function to `ggplot2::fortify(.....)`. This code also runs for `SpatialPolygons*` objects like `SpP` in your question. – Spacedman Jun 10 '15 at 07:20
  • NOOOO!!! The mean of the coordinates is **NOT** the centroid! Use `sp` method `coordinates(x)` or `rgeos::gCentroid`. – Spacedman Jun 10 '15 at 07:24
  • thanks for the pointer, @Spacedman! I spaced out and was thinking of the centroid of the point vertices, not the polygon... – Lucas Fortini Jun 10 '15 at 09:14
  • @qoheleth Did this answer your question? – Lucas Fortini Jun 12 '15 at 19:18