r - 将地理点分配给由 R tidyverse-method 中的多边形定义的组
问题描述
我有带有 x 和 y 坐标的产量数据。我想将每个屈服点分配给一个县。我有描述县的多边形。有没有办法在 R tidyverse 框架中做到这一点?
加载 ggplot2(只是为了帮助可视化)和 dplyr 包
library(ggplot2)
library(dplyr)
这是一个简单的示例数据集,有两个“县”,我称之为故事和爱情。
excnty <- tibble(
group = c(rep(1, 8), rep(2, 5)),
cnty = c(rep("story",8), rep("love", 5)),
order = c(seq(1:8), seq (1:5)),
Lat = c(3, 3, 3, 1, 1, 2, 2, 3,
2, 2, 1, 1, 2),
Lon = c(1, 2, 3, 3, 2, 2, 1, 1,
1, 2, 2, 1, 1))
这是产量数据的示例,分配了 x 和 y 坐标
expoints <- tibble(
yield = c(5, 10),
Lat = c(1.5, 2.5),
Lon = c(1.5, 2.5))
“县”和点的视觉效果
excnty %>%
ggplot(aes(Lat, Lon)) +
geom_polygon(aes(fill = group, group = group)) +
geom_point(data = expoints, aes(Lat, Lon), color = "red", size = 5)
所需的数据框如下
desired <-
expoints %>%
mutate(cnty = c("love", "story"))
desired
显然县的形状会变得更加复杂,我不确定如何自动化这个过程。任何帮助表示赞赏,我没有使用 raster 或 sp 或 sf 包,但认为它们可能有用吗?
解决方案
我提出了一个基于较新的 {sf} 包的工作流,特别st_intersection
是在空间上组合两个对象的功能(即,将县属性赋予位于该县的点)。
我在北卡罗来纳州使用三个半随机城市;没有其他原因,北卡罗来纳州的 shapefile 包含在 {sf} 包中,因此很容易获得。
另请注意,我st_transform
用于将两个空间对象的坐标参考系与一个公共的EPSG4326 = WGS84 对齐,否则会发生错误。
sf 包是管道友好的,但正式在 tidyverse 生态系统之外。
library(sf)
library(tidyverse)
# NC counties - a shapefile shipped with the sf package
shape <- sf::st_read(system.file("shape/nc.shp",
package ="sf")) %>%
sf::st_transform(4326) # because WGS84 is a good default
# three cities - note the x and y coordinates
points <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
x = c(-78.633333, -79.819444, -77.912222),
y = c(35.766667, 36.08, 34.223333)) %>%
sf::st_as_sf(coords = c("x","y"), crs=4326) # transform to sf object & WGS84 CRS
# a quick overview
ggplot() +
geom_sf(data = shape) +
geom_sf(data = points, aes(color = name), show.legend = "point")
#actual calculation
res <- points %>%
sf::st_intersection(shape) %>% # perform the intersection
dplyr::select(city = name, county = NAME) %>% # select relevant columns
sf::st_set_geometry(NULL) # geometry is no longer required
res
city county
2 Greensboro Guilford
1 Raleigh Wake
3 Wilmington New Hanover
推荐阅读
- reactjs - 鼠标离开上的错误光标动画
- r - R:mgcv add colorbar to 2D heatmap of GAM
- if-statement - 如何根据 Google 表格中的多个条件返回真或假?
- websocket - 如何在网络工作者中以角度使用 RxJS websocket
- unit-testing - 如何在服务器端模拟客户端 nextJs 动态导入?
- google-apps-script - 时间表,条目下方的颜色单元格
- html - ASP.Net 视图无法在代码块中的元素上设置边距
- python-3.x - Python Nslookup 域列表问题
- tfs - tf.exe 从哪里检索 TFS 服务器 URL?
- python - 如何使用换行格式数组删除第二个单词