我有一个地理编码点数据帧列表,我想将其与相应的多边形几何数据帧列表相交。以下是创建数据结构的表示:
library(dplyr)
library(purrr)
library(sf)
library(tigris)
# pull two Oregon counties and their polygons
counties <- counties(state = "OR")[1:2,] %>% dplyr::select(NAME, GEOID, geometry)
# split the dataframe into a list to emulate my real data
or_counties <- counties %>% split(.$GEOID)
# create random point data for the two counties and add the GEOID field (a unique state + county numeric index)
wallowa_pts = as.tibble(st_jitter(st_sample(counties[1,], 10), factor=0.2)) %>% mutate(GEOID = counties[1,]$GEOID)
crook_pts = as.tibble(st_jitter(st_sample(counties[2,], 10), factor=0.2)) %>% mutate(GEOID = counties[2,]$GEOID)
# bind and convert to sf
pts <- rbind(wallowa_pts, crook_pts) %>% st_as_sf()
# split to a list
or_pts <- pts %>% split(.$GEOID)
因此,我现在在一个列表中具有按 GEOID 分组的点数据,在另一个列表中具有也按 GEOID 分组的多边形数据。我需要在
or_pts
中的每个列表元素中创建一个新字段,指示 st_intersects()
对应列表元素上 or_counties
的评估结果,在本例中,将 T/F 重新编码为颜色以进行可视化。如果我像这样手动定义 or_counties
中的列表元素,我可以获得范围狭窄的结果:
or_pts %>%
map(
~ mutate(., status =
case_when(
st_intersects(., or_counties[[1]], sparse = F) == T ~ "green",
TRUE ~ "red"
)
)
)
但是,我想要的是动态地将来自
or_pts$41013
与 or_counties$41013
、or_pts$41063
与 or_counties$41063
的数据相交,以此类推,对数千个县的数万个点进行数据交叉,以识别地理编码错误。
这似乎是一个嵌套的
map2
/imap
工作,但我无法弄清楚它在这个过程中的位置。
map2
,如果列表对齐:
map2(or_pts, or_counties,
\(pts, poly) mutate(pts, status = if_else(st_intersects(pts, poly, sparse = FALSE), "green", "red" )))
imap
,如果需要使用or_pts
名称来访问or_counties
中对应的项目:
imap(or_pts,
\(pts, idx) mutate(pts, status = if_else(st_intersects(pts, or_counties[[idx]], sparse = FALSE), "green", "red" )))