R 中的 shapefile:通过相似属性聚合几何

问题描述

我有一个 SpatialpolygonsDataFrame (myshape) 格式的 shapefile,其中有几个子分区由同一区域的 A、B、C 等表示,例如。 LIMOEIRO064A、LIMOEIRO064B 等适用于多个不同领域。例如,我想合并 LIMOEIRO064 的几何图形。为此,我尝试:

# Packages
library(raster)
library(rgdal)

# Download and unzip the shapefile example
download.file('https://www.dropBox.com/s/2zoproayzqvj1cc/myshape.zip?dl=0',destfile="myshape.zip",method="auto") 
unzip(paste0(getwd(),"/myshape.zip"))

#Read target shapefile -----------------------------------------------
myshape <- readOGR (".","myshape") 
proj4string(myshape) <- CRS("+proj=longlat +ellps=GRS80 +no_defs")

# Create unique ID for each area without sub-units A,B,C,etc. if have in CD_TALHAO attribute
str(myshape@data)
#'data.frame':  419 obs. of  7 variables:
# $ OBJECTID  : chr  "563774" "563783" "795091" "795092" ...
# $ ID_PROJeto: chr  "131" "131" "131" "131" ...
# $ PROJeto   : chr  "LIMOEIRO" "LIMOEIRO" "LIMOEIRO" "LIMOEIRO" ...
# $ CD_TALHAO : chr  "064A" "017B" "V00204" "V00702" ...
# $ SHAPE_AREA: num  1.07e-05 1.67e-05 1.72e-07 2.46e-07 2.07e-06 ...
# $ SHAPE_LEN : num  0.02774 0.01921 0.00401 0.005 0.01916 ...
# $ CODE      : chr  "LIMOEIRO064A" "LIMOEIRO017B" "LIMOEIROV00204" "LIMOEIROV00702" ...
myshape@data$UNIQUE<-gsub("[a-zA-Z]","",myshape@data$CD_TALHAO)

# New unique CODE
myshape@data$CODE<-paste0(myshape@data$PROJeto,myshape@data$UNIQUE)
#unique(myshape@data$CODE)
#  [1] "LIMOEIRO064"     "LIMOEIRO017"     "LIMOEIRO00204"   "LIMOEIRO00702"   "LIMOEIRO06501"   "LIMOEIRO02403"  
#  [7] "LIMOEIRO00201"   "LIMOEIRO05002"   "LIMOEIRO03516"   "LIMOEIRO02203"   "LIMOEIRO02904"   "LIMOEIRO00405"  
# [13] "LIMOEIRO01804"   "LIMOEIRO01608"   "LIMOEIRO03106"   "LIMOEIRO00101"   "LIMOEIRO010"     "LIMOEIRO035"    
# [19] "LIMOEIRO020"     "LIMOEIRO001"     "LIMOEIRO056"     "LIMOEIRO059"     "LIMOEIRO06402"   "LIMOEIRO01801"
#...
# [295] "LIMOEIRO011"     "LIMOEIRO06408"

现在,我想在 new_myshape 中合并具有相同 CODE 标识的 shapefile 和几何图形,但我发现 bind()union() 之类的选项对我不起作用。我需要一些类似 myshape@data$CODE 的聚合或类似这样的选项。 请问有什么想法吗?

解决方法

您可以通过以下方式使用 terra

library(terra)
f <- system.file("ex/lux.shp",package="terra")
v <- vect(f)
va <- aggregate(v,"ID_1")

您可以对 raster/sp 使用相同的方法

p <- shapefile(system.file("external/lux.shp",package="raster"))
pa <- aggregate(p,"ID_1")