等价于sp包在多边形中的点/使用sf覆盖


16

我正在将代码从sp包迁移到较新的sf包。我之前的代码中有一个多边形SpatialDataFrame(censimentoMap)和一个SpatialPointDataFrame(indirizzi.sp),并使用下面的指令获取了放置在其中的每个点的多边形单元格ID(“ Cell110”):

points.data <- over(indirizzi.sp, censimentoMap[,"Cell110"])

实际上,我创建了两个SF对象:

shape_sf <- st_read(dsn = shape_dsn) shape_sf <- st_transform(x=shape_sf, crs=crs_string)indirizzi_sf = st_as_sf(df, coords = c("lng", "lat"), crs = crs_string)

而且我正在寻找上述说明的SF…可能是:

ids<-sapply(st_intersects(x=indirizzi_sf,y=shshape_sfpeCrif), function(z) if (length(z)==0) NA_integer_ else z[1]) cell_ids <- shape_sf[ids,"Cell110"]

Answers:


20

您可以使用st_join获得相同的结果:首先创建一个演示多边形和一些带有sf的点。

library(sf)
library(magrittr)

poly <- st_as_sfc(c("POLYGON((0 0 , 0 1 , 1 1 , 1 0, 0 0))")) %>% 
  st_sf(ID = "poly1")    

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))

现在在sp对象上使用over查看结果

over(as(pts, "Spatial"), as(polys, "Spatial"))
>#      ID
># 1 poly1
># 2 poly1
># 3  <NA>

现在相当于sf st_join

st_join(pts, poly, join = st_intersects)
># Simple feature collection with 3 features and 2 fields
># geometry type:  POINT
># dimension:      XY
># bbox:           xmin: 0.5 ymin: 0.5 xmax: 3 ymax: 3
># epsg (SRID):    NA
># proj4string:    NA
>#     ID.x  ID.y               .
># 1 point1 poly1 POINT (0.5 0.5)
># 2 point2 poly1 POINT (0.6 0.6)
># 3 point3  <NA>     POINT (3 3)

或完全相同的结果

as.data.frame(st_join(pts, poly, join = st_intersects))[2] %>% setNames("ID")

>#    ID
># 1 poly1
># 2 poly1
># 3  <NA>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.