使用 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")
最佳答案
在 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')
关于r - 用带孔的多边形制作 sf 对象并设置 crs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64055453/