在 sf 包中查找多边形点

时间:2021-05-27 14:52:32

标签: r geospatial sf sp

我正在尝试在 sf 中创建一个简单的多边形并仅选择该多边形内的点。我在这里做错了什么?

    library(concaveman)
    library(ggplot2)


    foo.df <- data.frame("long"=c(136,137,137,136),"lat"=c(36,36,37,37))
    foo.sf <- st_as_sf(foo.df, coords = c("long","lat"))
    poly <- concaveman(foo.sf) ## in case points are out of order
    point.df <- data.frame("long"=c(136.2,136.5,137.5),"lat"=c(36.5,36.5,36.5))
    point.sf <- st_as_sf(point.df, coords = c("long","lat"))

good_points <- st_join(point.sf,poly,join=st_within)

st_join 函数似乎没有做任何事情

  ggplot() + 
  geom_sf(data = poly) +
  geom_sf(data= good_points)

问题不在于凹人包

good_points <- st_join(point.sf,foo.sf,join=st_within)

ggplot() + 
  geom_sf(data = poly) +
  geom_sf(data= good_points)

而这种创建多边形的尝试会引发错误

another_poly <- st_polygon(list(as.matrix(foo.df)))
good_points <- st_join(point.sf,another_poly,join=st_within)

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找st_filter。这样,您将只获得在多边形内找到的点。 good points 对象现在只包含两个点,而不是三个点(就像在 OP 中一样)。

good_points <- st_filter(point.sf, poly)

# Simple feature collection with 2 features and 0 fields
# Geometry type: POINT
# Dimension:     XY
# Bounding box:  xmin: 136.2 ymin: 36.5 xmax: 136.5 ymax: 36.5
# CRS:           NA
#            geometry
# 1 POINT (136.2 36.5)
# 2 POINT (136.5 36.5)