Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

My goal is to modify an existing shapefile by merging certain polygons.

After importing the shapefile and using the UnionSpatialPolygons command, I get the polygon outline that I want.

However, this is now a SpatialPolygons object and not a SpatialPolygonsDataFrame, so I'm unable to export it to a shapefile using writeOGR.

How can I get around this problem?

Thanks in advance,

John

share|improve this question
    
If the answer below was useful, you should select it as the correct one by clicking on the tick mark to the left of the answer text. –  SlowLearner Jun 5 '13 at 17:37

1 Answer 1

As the name says, a SpatialPolygonsDataFrame is basically just a SpatialPolygons object with data attached (the attribute table). The data must have at least as many rows as there are features

library(rgdal)
ob <- SpatialPolygons(..)# Your SpatialPolygons Object
spp <-     SpatialPolygonsDataFrame(ob,data=as.data.frame("yourData"),proj4string=CRS("+proj=    aea > +ellps=GRS80 +datum=WGS84"))
writeOGR(spp,"shapes","testShape",driver="ESRI Shapefile",)

----EDIT----

If you want to convert your SpatialPolygonsDataFrame back to a SpatialPolygons object you just need to address the object structure within R

ob <- SpatialPolygons(spp@polygons,proj4string=spp@proj4string)
share|improve this answer
    
For sure, @Curlew is right. Make sure to specify IDs argument correctly when executing UnionSpatialPolygons. Otherwise you might get trouble specifying data argument when converting back to SpatialPolygonsDataFrame. –  flowla May 23 '13 at 13:18
    
+1. Would you know how to do the opposite? SpatialPolygonsDataFrame to SpatialPolygons object? –  Andre Silva Mar 12 at 21:15
1  
Sure, quite easy. I edited the original answer for that –  Curlew Mar 12 at 23:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.