-1

I'm working with a dataframe containing longitude and latitude for each point. I have a shapefile containing mutually exclusive polygons. I would like to find the index of the polygon it where each point is contained. Is there a specific function that helps me achieve this? I've been trying with the sf package, but I'm open to doing it with another one. Any help is greatly appreciated.

1 Answers1

1

I believe you may be looking for function sf::st_intersects() - in combination with sparse = TRUE setting it returns a list, which can be in this use case (points & a set of non-overlapping polygons) converted to a vector easily.

Consider this example, built on the North Carolina shapefile shipped with {sf}

library(sf)

# as shapefile included with sf package
shape <- st_read(system.file("shape/nc.shp", package="sf")) %>%  
    st_transform(4326) # WGS84 is a good default

# three semi random cities
cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                  x = c(-78.633333, -79.819444, -77.912222),
                  y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326) # again, WGS84

# plot cities on full map
plot(st_geometry(shape))
plot(cities, add = T, pch = 4)   

enter image description here

# this is your index
index_of_intersection <- st_intersects(cities, shape, sparse = T) %>% 
      as.numeric()

# plot on subsetted map to doublecheck
plot(st_geometry(shape[index_of_intersection, ]))
plot(cities, add = T, pch = 4)  

enter image description here

Jindra Lacko
  • 2,670
  • 2
  • 12
  • 26