寻找一个点包含在R中的多边形

Looking for a polygon where a point is contained in R

我正在处理一个包含每个点的经度和纬度的数据框。我有一个包含互斥多边形的 shapefile。我想找到包含每个点的多边形的索引。是否有特定功能可以帮助我实现这一目标?我一直在尝试使用 sf 包,但我愿意用另一个包来做。非常感谢任何帮助。

我相信您可能正在寻找函数 sf::st_intersects() - 结合 sparse = TRUE 设置它 returns 一个列表,在这个用例中可以是(点和一组非重叠多边形)轻松转换为矢量。

考虑这个例子,它建立在 {sf}

附带的北卡罗来纳州 shapefile 上
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)   

# 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)