问题描述
使用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,4,0),ncol = 2,byrow = TRUE)
hole <- matrix(c(1,1,2,1),byrow = TRUE)
outer2 <- matrix(c(5,5,6,5),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')