Skip to content
Prev 7420 / 29559 Next

Helping with write a function. Merging shape files?

Zia,

The error you received was 'invalid class "SpatialPolygons" object:
non-unique Polygons ID slot values'.
Renaming the Polygons IDs so that they are unique should fix your problem.

The following code along with some test shapefiles I used are attached.

library(rgdal)
setwd("C:/test")

# obtain shapefiles in current directory
files <- list.files(pattern = "shp")

# get polygons from first file
data.first <- readOGR(files[1], gsub(".shp","",files[1]))
polygons <- slot(data.first, "polygons")

# add polygons from remaining files
for (i in 2:length(files)) {
   data.temp <- readOGR(files[i], gsub(".shp","",files[i]))
   polygons <- c(slot(data.temp, "polygons"),polygons)
}

# rename IDs of Polygons
for (i in 1:length(polygons)) {
   slot(polygons[[i]], "ID") <- paste(i)
}

# ain't that spatial
spatialPolygons <- SpatialPolygons(polygons)
spdf <- SpatialPolygonsDataFrame(spatialPolygons,
data.frame(fakeData=1:length(polygons)))

# output combined results
plot(spatialPolygons)
writeOGR(spdf, dsn="C:/test/combined.shp", layer="combined", driver="ESRI
Shapefile")

# end of code

My test shapefiles had very different attribute tables, so I didn't bother
combining the data tables.
However, the code above should at least show you that your method can work.

I found it interesting that when I combined the polygons in the opposite
order:
polygons <- c(polygons,slot(data.temp, "polygons"))

the SoutheasternStates polygons completely covered up the Florida polygons
in QGis, but
the Florida polygons showed up when plotting in R:
plot(spatialPolygons)

Does the R 'plot' function order the polygons before displaying them? Is it
possible to view the code
for a function like plot(SpatialPolygons)?

Matt
On Wed, Jan 20, 2010 at 4:14 PM, Zia Ahmed <zua3 at cornell.edu> wrote:

            
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20100120/aa6ba726/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.zip
Type: application/zip
Size: 67885 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-geo/attachments/20100120/aa6ba726/attachment.zip>