Search code examples
rgeospatialr-sfr-sp

finding points with polygon in sf package


I'm trying to create a simple polygon in sf and select only points within that polygon. What am I doing wrong here?

    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)

The st_join function doesn't seem to do anything

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

The problem isn't with the concaveman package

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

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

And this attempt to create a polygon throws an error

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

What am I missing?


Solution

  • I think you are looking for st_filter. This way you'll get only the points that are found within the polygon. The good points object now contains only two points, instead of three (like in the 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)