I have a SpatialPolygons
object. This object has a single feature, a Polygons object, that is itself made up of multiple Polygon objects.
I'd like to subset the SpatialPolygons object so that the Polygons object only has a single Polygon object, which is the Polygon with the largest area.
I've tried many different approaches and can't figure out how to do the subsetting at a sub-Polygons level.
Here is an example:
#create polygon
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)))
Srs = Polygons(list(Sr1,Sr2), "s1/2")
SpP = SpatialPolygons(list(Srs))
In this example, SpP has a single Polygons object. The first sub-polygon of the Polygons object has area 5.5, and the second has area 1.5. I'd like to subset the SpatialPolygons object such that the Polygons object only has one Polygon, the one with area 5.5.
Is this possible?
EDIT
Calum You thank you for your answer. I've never used the sf package, but it looks cool. Especially since it plays so nicely with dplyr!
I ended up finding a different solution though. My main issue was that I didn't grasp how the SpatialPolygons object structure worked. A SpatialPolygons object contains 1..* Polygons objects, so the constructor takes a list of Polygons objects. A Polygons object contains 1..* Polygon objects, so the constructor takes a list of Polygon objects. With this in mind, I used the following solution.
plst <- SpP@polygons[[1]]@Polygons #get the list of Polygon objects
plst <- plst[which.max(sapply(plst,function(p) return(p@area)))] #filter to the max area
spoly2 <- SpatialPolygons(list(Polygons(plst,'id')))
Plot shows this will filter the rings by the largest area.
plot(SpP)
plot(spoly2,col=alpha('red',0.1),add=T)