【发布时间】:2021-01-11 06:40:18
【问题描述】:
使用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")
或者,我可以尝试使每个列表元素成为一个多边形并指定正确的 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")
【问题讨论】:
-
你似乎找到了答案;所以只是一个简短的说明 - 如果您需要从多边形中删除一个洞,请考虑
sf::st_sym_difference()