r - 用带孔的多边形制作 sf 对象并设置 crs

标签 r r-sf

使用 contourLines() 我已经提取了数据的 95% 轮廓。我想用正确的 crs 制作一个 sf 对象。虽然我无法分享我的实际数据集,但我改编了此 SO post 中的示例。来说明我陷入困境的地方。

主要问题是我的一个多边形中有一个洞,但我不知道如何制作一个 sf 对象,其中该洞被识别并且我可以在其中指定正确的crs。

我对 sf-package 还很陌生,还无法弄清楚这一点。以下是我到目前为止所尝试过的。我更新了 contourLines() 的输出,使其看起来像 pts,其中每个列表元素都是多边形的点坐标矩阵。使用 st_polygon() 将删除该洞...但随后我无法指定 crs:

library(sf)
library(dplyr)
library(purrr)

# data example
outer1 <- matrix(c(0,0,4,0,4,4,0,4,0,0), ncol = 2, byrow = TRUE)
hole   <- matrix(c(1,1,1,2,2,2,2,1,1,1), ncol = 2, byrow = TRUE)
outer2 <- matrix(c(5,5,5,6,6,6,6,5,5,5), ncol = 2, byrow = TRUE)
pts <- list(outer1, hole, outer2)

# removes hole, but can't add crs 
# - nothing to transform with st_transform() 
# - st_set_crs() throws error:
#  > Error in UseMethod("st_crs<-") : 
#  >  no applicable method for 'st_crs<-' applied to an object of class "c('XY', 'POLYGON', 'sfg')"
pl1 <- st_polygon(pts)
plot(pl1, col = "red")

image of pl1

或者,我可以尝试将每个列表元素设为多边形并指定正确的 crs...但随后我不知道如何删除该洞:

pl2 <- pts %>% map(function(pts.x) {
  pts.x %>%
    as.data.frame() %>%
    set_colnames(c("x", "y")) %>%
    st_as_sf(coords = c("x", "y"), crs = 32611) %>%
    summarise(geometry = st_combine(geometry)) %>%
    st_cast("POLYGON")
}) %>%
  bind_rows
plot(pl2, col = "red")

image of pl2

最佳答案

this例如,他们使用 st_polygon 然后使用 st_sfc。这似乎有效

pl1 <- st_polygon(list(outer1, hole)) %>%
  st_sfc(crs = 32611)

#----------
Geometry set for 1 feature 
geometry type:  POLYGON
dimension:      XY
bbox:           xmin: 0 ymin: 0 xmax: 4 ymax: 4
projected CRS:  WGS 84 / UTM zone 11N
POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0), (1 1, 1 2, ...

plot(pl1, col = 'red')

enter image description here

关于r - 用带孔的多边形制作 sf 对象并设置 crs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64055453/

相关文章:

r - 如何在 st_intersect 之后从几何集合中选择某些几何图形?

r - 在R中将多边形转换为sf

r - 使用 R 包 sf 编写带坐标的 CSV

r - 在ggplot中,如何在类别之间沿x和y轴制作网格?

r - 使用data.table标记组中的第一个(或最后一个)记录

r - 你如何在 R 中使用 ssh 连接到远程服务器

r - 矩阵和向量形式的数据点数量

r - 如何使用 R 找到具有不同土地利用分类的栅格的平均坡度?

r 从缺失值上方的单元格中复制值

r - geom_sf : scale_*_continuous has no effect