MD_1977
MD_1977

Reputation: 81

How to dissolve polygon in R and transferring original attribute information

I want to dissolve some polygons, and I am doing the following:

  1. Batching in the shapefile (DA.shp - sensitive information hence first two sample records and only first three columns shown)
  2. Batching in csv file called zone.csv that has the information for dissolving joining the zone.csv to DA (first five records shown due to sensitivity)
  3. Dissolving the joined shapefile
  4. Creating row IDs to make the dissolved shapefile into a polygondataframe for export.

It all goes smoothly, however, I want to carry the Zed and Criteria fields in my dissolved polygon, like one can using GIS. I have tried to search in vain, so any help will be appreciated.

library(rgeos)
library(rgdal)
library(sp)

# set working directory
wd <- setwd("c:/Personal/R")

# read DA shapefile
da <- readOGR(wd, "DA")
plot(da)
crs.shp <- proj4string(da)
da@data[1:2,1:3]    # check first two records

OBJECTID    DAUID CDUID
0        3 35204831  3520
1        5 35180720  3518

# batchin text file with  zone numbers

zones.csv <- read.csv(file="c:/personal/R/Variant1.csv", header=TRUE, sep=",")
zones.csv$DAUID <- as.character(zones.csv$DAUID)    # make DAUID as character for join
zones.csv[1:5,]

DAUID  zed   Criteria
1 35140110 3102 GGHM zones
2 35140111 3102 GGHM zones
3 35140112 3102 GGHM zones
4 35140113 3102 GGHM zones
5 35140114 3102 GGHM zones

da1 <- da    # save a copy
da1@data$DAUID <- as.character(da1@data$DAUID)    # make character field for join

da1@data <- merge(da1@data, zones.csv, by.x = "DAUID", by.y = "DAUID", all.x=T, sort=F)

# Now dissolve
zone.shp <- gUnaryUnion(da1, id = da1@data$zed.x)
plot(zone.shp)

# extract zone Id's to make dataframe
Gid <- sapply(slot(zone.shp, "polygons"), function(x) slot(x, "ID")) 

# Create dataframe with correct rownames
z.df <- data.frame( ID=1:length(zone.shp), row.names = Gid)  

# make Polygondataframe to export as shapefile
zone.shp.pdf <- SpatialPolygonsDataFrame(zone.shp, data=z.df)    
zone.shp.pdf@data$crit <- 
proj4string(zone.shp.pdf) <- CRS(proj4string(da))

Upvotes: 2

Views: 3124

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

Here is a self-contained reproducible example with some SpatialPolygons:

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

Create a data.frame, and so on.

Anyway, I think you can use raster::aggregate to solve your problem. Below is a simplified and improved script, but I cannot check if it works as I do not have your data.

library(raster)
da <- shapefile("c:/Personal/DA.shp")
zones <- read.csv("c:/personal/R/Variant1.csv", stringsAsFactors=FALSE)

da1 <- merge(da, zones, by="DAUID", all.x=TRUE)

# Now dissolve
zone.shp <- aggregate(da1, c('zed', 'Criteria'))

If you want to write this to a shapefile:

shapefile(zone.shp, 'file.shp')

Upvotes: 2

Related Questions