csv - How to dissolve polygon in R and transferring original attribute information -
i want dissolve polygons, , doing following:
- batching in shapefile (da.shp - sensitive information hence first 2 sample records , first 3 columns shown)
- batching in csv file called zone.csv has information dissolving joining zone.csv da (first 5 records shown due sensitivity)
- dissolving joined shapefile
- creating row ids make dissolved shapefile polygondataframe export.
it goes smoothly, however, want carry zed , criteria fields in dissolved polygon, 1 can using gis. have tried search in vain, 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 2 records objectid dauid cduid 0 3 35204831 3520 1 5 35180720 3518 # batchin text file 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 character 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 copy da1@data$dauid <- as.character(da1@data$dauid) # make character field join da1@data <- merge(da1@data, zones.csv, by.x = "dauid", by.y = "dauid", all.x=t, sort=f) # dissolve zone.shp <- gunaryunion(da1, id = da1@data$zed.x) plot(zone.shp) # extract zone id's make dataframe gid <- sapply(slot(zone.shp, "polygons"), function(x) slot(x, "id")) # create dataframe correct rownames z.df <- data.frame( id=1:length(zone.shp), row.names = gid) # make polygondataframe export shapefile zone.shp.pdf <- spatialpolygonsdataframe(zone.shp, data=z.df) zone.shp.pdf@data$crit <- proj4string(zone.shp.pdf) <- crs(proj4string(da))
you should provide self-contained reproducible example. example, spatialpolygons here:
libarary(raster) p <- shapefile(system.file("external/lux.shp", package="raster"))
create data.frame, , on.
anyway, think can use raster::aggregate
solve problem. below simplified , improved script, cannot check if works not have 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) # dissolve zone.shp <- aggregate(da1, c('zed', 'criteria'))
i want write shapefile:
shapefile(zone.shp, 'file.shp')
Comments
Post a Comment