【问题标题】:R: Subsetting and plotting a SpatialPoints objectR:子集和绘制一个 SpatialPoints 对象
【发布时间】:2015-07-10 19:27:00
【问题描述】:

这个问题似乎以不同的形式被问过几次,但我找不到正确的解决方案。我有一个带有多个多边形的 SpatialPoint 对象,并且想使用插槽“ID”对 one 多边形进行子集化和绘制。

使用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

但是如何使用这些信息来子集和绘制一个多边形?很高兴得到任何帮助,在此先感谢!

【问题讨论】:

    标签: r plot subset sapply sp


    【解决方案1】:

    可以使用[] 完成子集化。请参阅 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')])
    

    【讨论】:

    • 伙计...我现在觉得有点愚蠢:-/ 感谢您花时间解释显而易见的事情,我一定是在某个地方打了个结!
    • 哈,你不是唯一的一个......在我找到旧的 [1] 之前,我正在尝试诸如 SpS[[1]]、subset、SpS$s1 之类的东西;)。
    • .. 或者更简单,plot(SpP['s2',])
    猜你喜欢
    • 2022-01-19
    • 2012-02-27
    • 1970-01-01
    • 2020-02-28
    • 2015-09-01
    • 2020-12-27
    • 2016-03-10
    • 1970-01-01
    • 2013-06-03
    相关资源
    最近更新 更多