在shapefile中合并单元,同时在R中保持其他单元的粒度

cidc1ykv  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个德国的5位数邮政编码shapefile。大数字1位邮政编码与德国各州相似。我用rgdal读取shapefile数据,因此有SpatialPolygonsDataFrame。我只有德国部分地区的数据,即。一些邮政编码。我喜欢用5位数的粒度来展示我所拥有的数据。使用leaflet来创建一个Map,它使我花了很长时间来绘制所有的近10.000个邮政编码。因此,我喜欢“summarize”/“合并”/“merge”那些没有数据的邮政编码的外边界(值为NA)。

# German postcode shapes 

# Create temp files
temp <- tempfile()
temp2 <- tempfile()

# Download the zip file and save to 'temp' 
URL <- "https://downloads.suche-postleitzahl.org/v2/public/plz-5stellig.shp.zip"
download.file(URL, temp)

# Unzip the contents of the temp and save unzipped content in 'temp2'
unzip(zipfile = temp, exdir = temp2)

# Read shape file 
library(rgdal)
GER_postcode <- readOGR(temp2)

head(GER_postcode@data$note)

# Create subsample 
library(tidyverse)

GER_postcode@data$einwohner2 <- ifelse(substr(GER_postcode@data$plz, 1, 1) %in% c("0", "1", "7"), GER_postcode@data$einwohner, NA)

# Plot Subsample 
library(leaflet)

qpal <- colorBin("Reds", GER_postcode@data$einwohner2, bins=10)

leaflet(GER_postcode) %>%
  addPolygons(stroke = TRUE,opacity = 1,fillOpacity = 0.5, smoothFactor = 0.5,
              color="black",fillColor = ~qpal(einwohner2),weight = 1) %>%
  addLegend(values=~einwohner2,pal=qpal,title="Population")

字符串
我怎样才能使Map显示这些邮政编码形状的值,并合并所有其他的值是NA
x1c 0d1x的数据
我正在查看library(rgeos)gUnaryUnion(),它们将shapefile中的所有单位单位都单位到外部边界。虽然我只需要在一个子集上这样做。

aurhwmvo

aurhwmvo1#

我个人会使用过滤器/子集删除不相关的多边形,并使用国家轮廓作为一个单独的背景层。Outline可以通过联合邮政编码形状来构建,不过下载一个邮政编码形状(或者安装一些捆绑了国家形状的包)可能会更快
由于rgdalregos将在几个月内退役,因此下面的示例使用sf(以及可选的geos包)。

library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(dplyr)
library(leaflet)

URL <- "https://downloads.suche-postleitzahl.org/v2/public/plz-5stellig.shp.zip"

# use GDAL virtual file systems to load zipped shapefile from remote url
GER_postcode <- paste0("/vsizip//vsicurl/", URL) %>%  read_sf()

# country outline from giscoR
GER_outline <- giscoR::gisco_get_countries(country = "DE")

# if it must be built from input shapes, we can use sf::st_union() or switch  
# to geos (the R library), it performs bit better in this case:

# GER_outline <- as_geos_geometry(GER_postcode) %>% 
#   geos_make_collection() %>% 
#   geos_unary_union() %>% 
#   st_as_sfc()

GER_postcode_subsample <- GER_postcode %>% filter(substr(plz, 1, 1) %in% c(0, 1, 7))

# Plot Subsample 
qpal <- colorBin("Reds", GER_postcode_subsample$einwohner, bins=10)

leaflet(GER_postcode_subsample) %>%
  addPolygons(data = GER_outline, smoothFactor = 0.5,
              color="black", fillColor = "#808080", weight = 1) %>% 
  addPolygons(stroke = TRUE,opacity = 1,fillOpacity = 0.5, smoothFactor = 0.5,
              color="black",fillColor = ~qpal(einwohner),weight = .2) %>%
  # append NA to values to include it in legend
  addLegend(values=c(~einwohner, NA),pal=qpal,title="Population")

字符串
x1c 0d1x的数据
创建于2023-07-17带有reprex v2.0.2

相关问题