R: Subsetting and constructing SpatialPoints

This question seems to have been asked a couple of times in different forms, but I couldn't find the right solution. I have a SpatialPoint with multiple polygons and would like to multiply and plot one polygon using the "ID" slot.

Using the example from this question:

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)))
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)

      

I can extract the IDs of a SpatialPolygons object

SpP@polygons[[1]]@ID # one ID
sapply(SpP@polygons, function(x) x@ID) # all IDs

      

But how can I use this information to subset and plot one polygon? Glad for any help, thanks in advance!

+3


source to share


1 answer


Substitution can be done with []

. See the SpatialPolygons ( ?'SpatialPolygons-class'

) class reference :

Methods [...]:
[ : select subset of (sets of) polygons; NAs are not permitted in the row index"

      



So, using your data:

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)

# plot single polygon
par(mfrow=c(3,1))
plot(SpP[1])
plot(SpP[3])

# or using IDs: retrieve list of all IDs
IDs = sapply(SpP@polygons, function(x) x@ID)

# plot polygon with specific ID
plot(SpP[which(IDs == 's2')])

      

+1


source







All Articles