我想解散一些多边形,我正在做以下事情:
一切顺利,但是,我想在我的溶解多边形中携带Zed和Criteria字段,就像可以使用GIS一样。我试图徒劳地搜索,所以任何帮助都将受到赞赏。
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))
答案 0 :(得分:2)
您应该提供一个独立的可重复示例。例如,在这里获取一些SpatialPolygons:
libarary(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
创建data.frame,依此类推。
无论如何,我认为您可以使用raster::aggregate
来解决您的问题。下面是一个简化和改进的脚本,但我无法检查它是否有效,因为我没有你的数据。
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'))
我想将它写入shapefile:
shapefile(zone.shp, 'file.shp')