finding points with polygon in sf package
Asked Answered
T

1

8

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?

Tonnie answered 27/5, 2021 at 14:52 Comment(2)
I am trying to remember... maybe using st_intersection(point.sf,poly)? Not completely sureDiaconicum
YES! That works perfectly on the poly object. BUT on another_poly it returns one point instead of two!Tonnie
N
18

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)
Nectar answered 27/5, 2021 at 15:10 Comment(2)
Yes, that's it . . . and it also works with the another_poly object I created directly from the points! sf isn't "simple" but it does play nicely with ggplot!Tonnie
Thank you! this is exactly the function that I needed!Rematch

© 2022 - 2024 — McMap. All rights reserved.