Miao  Cai
Miao Cai

Reputation: 1014

find the state where the points are located in, `sf` r

I have a lot of points generated from satellite images, and I want to find where the points are (states). I searched for some links and got a clue that I should use sf::st_intersects, but it turns out not to work. Here is a minimal example:

library(sf)
library(ggplot2)
library(dplyr)

# Contiguous US state boundaries
usa = st_as_sf(maps::map("state", fill = TRUE, plot = FALSE))

# Simulate some random points
pts = data.frame(
  x = c(-91.6, -74.3, -101.5),
  y = c(36.1, 42.1, 25.3)
  ) %>%
  st_as_sf(coords=c("x", "y"), crs = 4326)

ggplot() +
  geom_sf(data = usa, fill = NA) +
  geom_sf(data = pts,
          shape = 21, size = 4, fill = "red") +
  coord_sf(crs = st_crs(102003)) +
  theme_minimal()

Here is the resultant figure: enter image description here What I want to have is the pts data.frame with one more row indicating the state of the points:

             geometry  state
1  POINT (-91.6 36.1)  arkansas
2  POINT (-74.3 42.1)  new york
3  POINT (-101.5 25.3) NA

I know I should show sf::st_transform, but did not succeed in doing that. Ideally I want the intersect to be scalable since I have more than 1,000,000,000 points.

Thank you!

Upvotes: 2

Views: 401

Answers (2)

william3031
william3031

Reputation: 1708

You can use st_join.

a <- pts %>% 
  st_join(usa)

> a 
Simple feature collection with 3 features and 1 field
geometry type:  POINT
dimension:      XY
bbox:           xmin: -101.5 ymin: 25.3 xmax: -74.3 ymax: 42.1
epsg (SRID):    4326
proj4string:    +proj=longlat +datum=WGS84 +no_defs
        ID            geometry
1 arkansas  POINT (-91.6 36.1)
2 new york  POINT (-74.3 42.1)
3     <NA> POINT (-101.5 25.3)

Upvotes: 3

asfa
asfa

Reputation: 66

int = st_intersects(pts, usa)
sapply(int, function(x) if(length(x) == 0) NA else as.character(usa$ID[x]))
#[1] "arkansas" "new york" NA  

Upvotes: 2

Related Questions