我想创建一个新的 shapefile 或一个新的几何变量,以允许我在 R 中绘制区域周围的边界。我使用sf和 映射与tmap. 基本上,我正在向sf对象添加字符向量,并希望将字符向量设为新的/首选映射边框。
这是我的方法的一个例子,它没有做我想要的。我不能说它有什么作用。
library(tidyverse)
library(sf)
library(tmap)
## use North Carolina example
nc = st_read(system.file("shape/nc.shp", package="sf"))
nc_new.region <- nc %>% ## add new region variable
mutate(new.region = sample(c('A', 'B', 'C'), nrow(.),replace = T))
nc_union <- nc_new.region %>%
group_by(new.region) %>% # group by the new character vector
mutate(new_geometry = st_union(geometry)) # union on the geometry variable
# map with tmap package
tm_shape(nc_union)+
tm_borders()
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为mutate(new_geometry = st_union(geometry))在原始 sf 对象中创建了一个“新”列,但绘图仍然使用“原始”几何列。事实上,如果您查看一下您的nc_union对象,您会发现它仍然包含 100 个特征(因此,并没有真正完成“分解”)。
为了做你想做的事,你应该使用summarize组创建一个“新的” sf 对象:
library(tidyverse)
library(sf)
library(tmap)
## use North Carolina example
nc = st_read(system.file("shape/nc.shp", package="sf"))
#> Reading layer `nc' from data source `D:\Documents\R\win-library\3.5\sf\shape\nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type: MULTIPOLYGON
#> dimension: XY
#> bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> epsg (SRID): 4267
#> proj4string: +proj=longlat +datum=NAD27 +no_defs
nc_new.region <- nc %>% ## add new region variable
mutate(new.region = sample(c('A', 'B', 'C'), nrow(.),replace = T))
nc_union <- nc_new.region %>%
group_by(new.region) %>%
summarize()
> nc_union
Simple feature collection with 3 features and 1 field
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
epsg (SRID): 4267
proj4string: +proj=longlat +datum=NAD27 +no_defs
# A tibble: 3 x 2
new.region geometry
<chr> <MULTIPOLYGON [°]>
1 A (((-78.65572 33.94867, -79.0745 34.30457, -79.04095 34.3193, -79.02947 34.34737, -7~
2 B (((-79.45597 34.63409, -79.6675 34.80066, -79.68596 34.80526, -79.66015 34.8179, -7~
3 C (((-78.65572 33.94867, -78.63472 33.97798, -78.63027 34.0102, -78.58778 34.03061, -~
tm_shape(nc_union)+
tm_borders()
Run Code Online (Sandbox Code Playgroud)
您可以看到现在nc_union仅包含 3 个 MULTIPOLYGONS,并且 plot 反映了“聚合”。

另见:https : //github.com/r-spatial/sf/issues/290
由reprex 包(v0.3.0)于 2019 年 8 月 23 日创建