【问题标题】:Make sf object out of polygons with holes and set crs用带孔的多边形制作 sf 对象并设置 crs
【发布时间】: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()

标签: r sf


【解决方案1】:

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')

【讨论】:

  • 我一直在浏览那个小插曲,但仍然错过了这个 - 非常感谢你把这个说得这么清楚。
猜你喜欢
  • 2019-03-10
  • 2018-10-18
  • 2017-12-08
  • 2022-01-17
  • 2016-10-06
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多