sf包:提取,剪切和返回多边形

时间:2019-05-21 22:53:53

标签: r sf

我有一个sf表,我需要在其中提取一个多边形,将其裁剪到边界框,然后将其写回到sf,以便可以使用一个修改后的多边形绘制原始图。我想出了所有方法,只不过将修改后的多边形写回原始科幻小说。

这是使用sf包中的NC数据集的可复制示例。我在county_clipped回到nc数据集的地方出现错误。我在这里需要做什么?

#Read NC shape from sf package
nc <- st_read(system.file("shape/nc.shp", package="sf"))

#extract county of interest
county <-nc[[1,"geometry"]]

#construct polygon to be clipped
bboxpolygon = st_polygon(list(rbind(c(-81.65,36.23), 
                                     c(-81.65,36.45), 
                                     c(-81.23,36.45), 
                                     c(-81.23,36.23), 
                                     c(-81.65,36.23))))
#Plot bounding box and county
par(mar = c(0,0,1,0))
plot(county)
plot(bboxpolygon, add=TRUE)   

#clip county
county_clipped <-st_intersection(county,bboxpolygon)

#confirm clipping worked
plot(county_clipped)

#write revised polygon back to dataset
nc[1,"geometry"]<-county_clipped

#plot revised object
plot(nc$geometry)

1 个答案:

答案 0 :(得分:2)

geometry对象中的sf列是sfc对象,它是sfg对象的集合。

attr( nc, "class" )
# [1] "sf"         "data.frame"

attr( nc$geometry, "class" )
# [1] "sfc_MULTIPOLYGON" "sfc"

您的county_clipped对象是sfg

attr( county_clipped, "class" )
# [1] "XY"      "POLYGON" "sfg"

因此,为了更新“几何”,它必须是sfc对象

nc[1,"geometry"] <- sf::st_sfc( county_clipped )

注意,对于这种新形状,面积,PERIMETER和其他属性将不正确

相关问题