3

I only recently started playing with shapefiles and R packages for manipulating them. I am looking at creating a new shapefile based on merged polyons by following this example, however, I cannot seem to figure out what I am suppose to feed the as.data.frame("youData").

Using the Zambia shapefiles as an example, how would one go about creating a new shapefile composed of a superset district-level data?

require(maptools)
require(rgadl)

zambia <- readShapeSpatial("ZMB_adm2.shp")
zambiap <- unionSpatialPolygons(zambia, ID=zambia@data$ID_1)

zambiapd <-     SpatialPolygonsDataFrame(ob,data=as.data.frame("yourData"),proj4string=CRS("+proj=    aea > +ellps=GRS80 +datum=WGS84"))
writeOGR(zambiapd,"shapes","testShape",driver="ESRI Shapefile",)
2

the str( ) will display the internal structure of your object

str(zambiap)

If you just want a data.frame to export:

dt<-data.frame(1:length(zambiap))
zambiapd <- SpatialPolygonsDataFrame(zambiap, data=dt)

If you want a meaningful data.frame, you need to get the data from the zambiap object.

dt.f<-NULL
for (i in 1:length(zambiap)){
dt<-zambiap@polygons[[i]]@area
dt.f<-rbind(dt.f, dt)
}

rownames(dt.f)<-1:length(zambiap)
dt.f<-data.frame(dt.f)
  • This can be done in a more elegant way, but I think that in this manner you can follow the idea based on the str( ) outputs above.

And then, you add the data, to your original object.

zambiapd <- SpatialPolygonsDataFrame(zambiap, data=dt)

To inspect the data.frame:

zambiapd@data

To manipulate the data.frame:

colnames(dt.f)<-("Area")
zambiapd@data<-dt.f

Be careful when manipulating the @data, adding more data, etc.

See this post: https://stackoverflow.com/questions/3650636/how-to-attach-a-simple-data-frame-to-a-spatialpolygondataframe-in-r

I am not sure if your proj4string parameters are correct.

For exporting your spdf:

writeOGR(zambiapd, dsn=getwd(), "Zambiapd", driver="ESRI Shapefile")

HTH,

  • 1
    Thank you for this. How would I preserve some of the original descriptive information from the original shapefile though? The output shapefile only have one column---Area in this case. – lightonphiri Nov 8 '14 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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