r – 如何使用st_join()使用sf包进行空间连接

前端之家收集整理的这篇文章主要介绍了r – 如何使用st_join()使用sf包进行空间连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是一个玩具的例子,我一直在摔跤
# Make points
point1 <- c(.5,.5)
point2 <- c(.6,.6)
point3 <- c(3,3)
mpt <- st_multipoint(rbind(point1,point2,point3))  # create multipoint

# Make polygons
square1 <- rbind(c(0,0),c(1,1),c(0,0))
square2 <- rbind(c(0,c(2,2),0))
square3 <- rbind(c(0,c(-1,-1),0))
mpol <- st_multipolygon(list(list(square1),list(square2),list(square2)))  # create multipolygon

# Convert to class' sf'
pts <- st_sf(st_sfc(mpt))
polys <- st_sf(st_sfc(mpol))

# Determine which points fall inside which polygons
st_join(pts,polys,join = st_contains)

最后一行生产

Error in as.data.frame.default(x[[i]],optional = TRUE,stringsAsFactors = stringsAsFactors) : 
  cannot coerce class "c("sfc_MULTIPOINT","sfc")" to a data.frame

如何做一个空间连接来确定哪些点落在哪个多边形?

解决方法

我也在围绕sf包的功能,所以道歉,如果这是不正确的或有更好的方法.我认为这里的一个问题是,如果你在你的例子中建立几何体,那么你不会得到你的想法:
> pts
Simple feature collection with 1 feature and 0 fields
geometry type:  MULTIPOINT
dimension:      XY
bBox:           xmin: 0.5 ymin: 0.5 xmax: 3 ymax: 3
epsg (SRID):    NA
proj4string:    NA
                     st_sfc.mpt.
1 MULTIPOINT(0.5 0.5,0.6 0.6...

> polys
Simple feature collection with 1 feature and 0 fields
geometry type:  MULTIPOLYGON
dimension:      XY
bBox:           xmin: 0 ymin: 0 xmax: 2 ymax: 2
epsg (SRID):    NA
proj4string:    NA
                    st_sfc.mpol.
1 MULTIPOLYGON(((0 0,1 0,1 ...

您可以看到,您在pts和poly中只有一个“功能”.这意味着您正在构建一个“多边形”功能(即由3个部分组成的多边形),而不是三个不同的多边形.点数也一样.

在挖了一下之后,我发现使用WKT符号来形成不同的(在我看来更容易)的方式来构建几何体:

polys <- st_as_sfc(c("POLYGON((0 0,0 1,1 1,0 0))","POLYGON((0 0,0 2,2 2,2 0,0 0 ))",0 -1,-1 -1,-1 0,0 0))")) %>% 
  st_sf(ID = paste0("poly",1:3))    

pts <- st_as_sfc(c("POINT(0.5 0.5)","POINT(0.6 0.6)","POINT(3 3)")) %>%
  st_sf(ID = paste0("point",1:3))

> polys
Simple feature collection with 3 features and 1 field
geometry type:  POLYGON
dimension:      XY
bBox:           xmin: -1 ymin: -1 xmax: 2 ymax: 2
epsg (SRID):    NA
proj4string:    NA
     ID                              .
1 poly1 POLYGON((0 0,1 0...
2 poly2 POLYGON((0 0,2 0...
3 poly3 POLYGON((0 0,...

> pts
Simple feature collection with 3 features and 1 field
geometry type:  POINT
dimension:      XY
bBox:           xmin: 0.5 ymin: 0.5 xmax: 3 ymax: 3
epsg (SRID):    NA
proj4string:    NA
      ID              .
1 point1 POINT(0.5 0.5)
2 point2 POINT(0.6 0.6)
3 point3     POINT(3 3)

你可以看到现在,poly和pts有三个特征.

我们现在可以找到“交叉矩阵”:

# Determine which points fall inside which polygons
pi <- st_contains(polys,pts,sparse = F) %>% 
  as.data.frame() %>% 
  mutate(polys = polys$ID) %>% 
  select(dim(pi)[2],1:dim(pi)[1])
colnames(pi)[2:dim(pi)[2]] = levels(pts$ID)

> pi
  polys point1 point2 point3
1 poly1   TRUE   TRUE  FALSE
2 poly2   TRUE   TRUE  FALSE
3 poly3  FALSE  FALSE  FALSE

意义(在注释中指出@symbolixau),多边形1和2包含点1和2,而多边形3不包含任何点.点3不是包含在任何多边形中.

HTH.

猜你在找的MsSQL相关文章