4

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

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

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?

1 Answer 1

3

You can use st_intersects() and it will let you know which points are within the polygon.

Add st_intersects(poly, goodpoints)[[1]] and it will return [1] 1 2.

If you add coordinate points 136.1, 36.1 to your list it will return [1] 1 2 4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.