寻找R中包含点的多边形

时间:2020-06-29 22:57:35

标签: r geospatial spatial shapefile sf

我正在处理一个包含每个点的经度和纬度的数据框。我有一个包含互斥多边形的shapefile。我想找到包含每个点的多边形的索引。有帮助我实现这一目标的特定功能吗?我一直在尝试sf软件包,但我愿意与另一个软件包一起使用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我相信您可能正在寻找函数sf::st_intersects()-与sparse = TRUE结合使用时,它会返回一个列表,该列表可以在此用例(点和一组不重叠的多边形)中转换轻松转换为向量。

考虑此示例,该示例基于{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)   

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