r longest line for each polygon spatial dataframe?

Viewed 281

how can i get the length of the longest line (side) of each polygon? what package would be least problematic? I wonder if there is any function other than iterating point by point (some dummy example below)? Other than that I wonder if there is any method of getting bearings and or angles of each segment versus neighbours, but as some experts are overly sensitive about asking only one question at a time I will leave it for any other time;) Thanks in advance

r1 = cbind(c(180114, 180553, 181127, 180114), c(332349, 332057, 332342, 332349))
r2 = cbind(c(180042, 180545, 180553,  180042), c(332373, 332026, 331426, 332373))
r3 = cbind(c(179110, 179907, 180433, 179110),  c(331086, 330620, 330494, 331086))
r4 = cbind(c(180304, 180403,179632,180304),  c(332791, 333204, 333635, 332791))
sr1=Polygons(list(Polygon(r1)),"r1")
sr2=Polygons(list(Polygon(r2)),"r2")
sr3=Polygons(list(Polygon(r3)),"r3")
sr4=Polygons(list(Polygon(r4)),"r4")
sr=SpatialPolygons(list(sr1,sr2,sr3,sr4))
srdf=SpatialPolygonsDataFrame(sr, data.frame(cbind(1:4,5:2),
                                             row.names=c("r1","r2","r3","r4")))
2 Answers

Using an R package called GeoAxe you can split geospatial objects into pieces. Once you have the segments individually, you can use another package called SpatialLines to get the segments' lengths. From here you can select the greatest one.

A possible downside of this method for you is that the data must be a spatial format e.g. .shp for input but luckily there is also a package for creating these.

Does this help ?

splitPolygon <- function(x){
  st_segment = function(r){st_linestring(t(matrix(unlist(r), 2, 2)))}
  m <- data.frame(st_coordinates(x)[, 1:2])
  nr <- nrow(m)
  m2 <- cbind(m[-nr,], m[-1,])
  names(m2) <- c("Xstart", "Ystart", "Xend", "Yend")
 m3 <- rbind(m2,
             data.frame(Xstart = m$Xend[nr],
                        Ystart = m$Yend[nr],
                        Xend = m$Xend[1],
                        Yend = m$Yend))
 m3$geom = st_sfc(sapply(1:nrow(m3), 
                         function(i){st_segment(m3[i,])},simplify=FALSE))
 st_sf(m3, crs = st_crs(x))
}

longest_side_of_polygon <- function(x){
  df <- splitPolygon(x)
  l <- st_length(df)
  lmat <- st_coordinates(df[which.max(l), ])[,1:2]
  st_sfc(st_linestring(rbind(lmat[1,], lmat[2,])),
         crs = st_crs(x))
}
Related