R:子集和绘制SpatialPoints对象

似乎这个问题已经被问过几次不同的形式,但我找不到合适的解决方案.我有一个带有多个多边形的SpatialPoint对象,并希望使用插槽“ID”对一个多边形进行子集和绘图.

使用this问题中的示例:

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)

我可以提取SpatialPolygons对象的ID

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

但是,如何使用此信息对单个多边形进行子集和绘图?很高兴得到任何帮助,提前谢谢!

最佳答案 可以使用[]完成子设置.请参阅SpatialPolygons类帮助(?’SpatialPolygons-class’):

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

所以使用你的数据:

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')])
点赞