R中几何集合中的并集多边形

R中几何集合中的并集多边形,r,data.table,sf,R,Data.table,Sf,有时我会得到一个多边形的shp层。为了进行分析,我需要它们和另一层shapefile之间的交集。不幸的是,我得到的大多数shp都有一些拓扑错误。我通常在qgis中自动更正它们(使用工具:fix geometry;我还尝试在sf中使用st_make_有效),但在与R包“sf”相交后,我仍然在geometrycollection类型中获得了大量混合在一起的点和线串。所以我的问题是如何从每一行的geometrycollection中提取并合并多边形 我尝试了这个代码,但它有点难看。我想要一些更直接、更

有时我会得到一个多边形的shp层。为了进行分析,我需要它们和另一层shapefile之间的交集。不幸的是,我得到的大多数shp都有一些拓扑错误。我通常在qgis中自动更正它们(使用工具:fix geometry;我还尝试在sf中使用st_make_有效),但在与R包“sf”相交后,我仍然在geometrycollection类型中获得了大量混合在一起的点和线串。所以我的问题是如何从每一行的geometrycollection中提取并合并多边形

我尝试了这个代码,但它有点难看。我想要一些更直接、更快的解决方案。正如您所看到的,我更喜欢使用data.table和sf包

#intersection of two shp
int=st_intersection(var,ods_g)
setDT(int)

## extract rows with geometrycollection type
int2=int[st_geometry_type(geometry)%in% c("GEOMETRYCOLLECTION")]

## extract rows with polygon in geometrycollection type
int2[, l:=length(st_collection_extract(geometry,"POLYGON")),by = seq_len(nrow(int2))]
int3=int2[l>0]

##union all polygon from geometrycollection in each row
int3[,geometry:=st_as_sf(st_union(st_collection_extract(geometry,"POLYGON"))),by = seq_len(nrow(int3))]


##without converting from sf to sp and back I got error: "Error in CPL_gdal_dimension(st_geometry(x), NA_if_empty) :attr classes has wrong size: please file an issue" what wolud be the reason for that error and what converting to sp 
int3=st_as_sf(as(st_as_sf(int3),"Spatial"))
此错误的原因是什么?转换到sp类会对几何图形产生什么影响?因为从“sp”类转换回“sf”类后,错误不会再次显示


谢谢

他们的原始形状文件有错误吗?您好,是的,他们的原始shp有错误