R:子集化和绘制 SpatialPoints 对象

标签 r plot subset sapply r-sp

这个问题似乎已经以不同的形式被问过几次,但我找不到正确的解决方案。我有一个带有多个多边形的 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')])

关于R:子集化和绘制 SpatialPoints 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29978826/

相关文章:

r - 计算 emmeans 对比度的自定义函数

r - 绘制 R map 的循环中有什么问题?

matlab - 使用 Matlab 在功率谱分析图上检测并标记最大峰值?

image - 在matlab中为矩阵着色

r - 如何按组拆分数据框?

r - 从数据框中提取具有最高值和最低值的行

r - 在 R 中使用 OR 条件和字符串进行子集化

r - ggplot stacked bar - 隐藏标签但保留标签定位

r - 自动创建 person 的 "age at event"变量的过程

使用 dplyr 管道替换对角线元素