如何在st_intersect之后从geometrycollection中选择某些几何?

rbl*_*030 4 r spatial r-sf

我正在使用梦幻般的新sf包运行两个多边形或其他sf对象的相交。与此类似:

a <- st_polygon(list(cbind(c(0,0,7.5,7.5,0),c(0,-1,-1,0,0))))
b <- st_polygon(list(cbind(c(0,1,2,3,4,5,6,7,7,0),c(1,0,.5,0,0,0.5,-0.5,-0.5,1,1))))
i <- st_intersection(a,b)
## GEOMETRYCOLLECTION(POINT(1 0), LINESTRING(4 0, 3 0), POLYGON((5.5 0, 7 0, 7 -0.5, 6 -0.5, 5.5 0)))
Run Code Online (Sandbox Code Playgroud)

我如何只保留POLYGONGEOMETRYCOLLECTION?在要素集合中选择不同类型非常容易,但是我似乎无法在sf包中找到与ST_CollectionExtract等效的类型。

Séb*_*tte 5

输出是一个列表,以便您可以在i[[3]]此处提取。
如果您以更标准的方式查找哪个元素是多边形,请使用:

w.pol <- purrr::map_lgl(i, ~st_is(.x, c("POLYGON", "MULTIPOLYGON")))
pol <- i[[which(w.pol)]]

##> pol
## POLYGON((5.5 0, 7 0, 7 -0.5, 6 -0.5, 5.5 0))
Run Code Online (Sandbox Code Playgroud)

编辑:如果有sfc,则可以使用st_cast来分隔要素类型,然后选择感兴趣的行:

# Simple feature data frame of spatial collection
a1 <- st_sf(a=1, geom = st_sfc(i))
a2 <- st_sf(a=2, geom = st_sfc(i))

ii <- rbind(a1, a2)

# Use st_cast to separate all features types
st_cast(ii)[which(st_is(st_cast(ii), c("POLYGON", "MULTIPOLYGON"))),]
Run Code Online (Sandbox Code Playgroud)

编辑:2017-12-23

您可以直接使用:

st_collection_extract(i, "POLYGON") 
Run Code Online (Sandbox Code Playgroud)