将地理点分配给R tidyverse方法中的多边形定义的组

时间:2019-09-11 15:45:43

标签: r dplyr raster sp sf

我有带有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软件包,但认为它们可能有用吗?

1 个答案:

答案 0 :(得分:2)

我提出了一个基于更新的{sf}程序包的工作流,特别是功能st_intersection,该功能在空间上结合了两个对象(即,将县属性赋予位于该县的点)。

我正在使用北卡罗来纳州的三个半随机城市;出于其他原因,{sf}软件包中包含了北卡罗来纳州的shapefile,因此很容易获得。

还请注意,我正在使用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") 

go tar heels!

#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