I have a shapefile in SpatialPolygonsDataFrame (myshape
) format with several sub-divisions represents by A, B, C, etc. of the same area eg. LIMOEIRO064A, LIMOEIRO064B, etc. for several different areas. I'd like to merge the geometries of LIMOEIRO064 for example. For this I try:
# 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"
Now, I'd like to merge shapefiles and geometries with the same CODE identification in a new_myshape
but I find options like bind()
and union()
not work for me. I need something like aggregate by myshape@data$CODE
or some option like this.
Please any ideas?
Here is how you can do that with terra
library(terra)
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
va <- aggregate(v, "ID_1")
You can use the same approach with raster/sp
p <- shapefile(system.file("external/lux.shp", package="raster"))
pa <- aggregate(p, "ID_1")