Friday, 4 August 2017

r - How to convert a spatialpolygon to a SpatialPolygonsDataFrame and add a column to the attribute table


coast<-readShapeSpatial("coastline.shp")
landc<-readShapeSpatial("landcover.shp")

ro<-readShapeSpatial("roads.shp")
bc<-gBuffer(ro,width=100)
landc$ratings=1
landc$ratings[landc$LANDUSE_ID==4]=0

Above, I take any category that has 4 and in the new column put it as 0.


At this point, I want the column named ratings as well for the bc, where it will take 0 if it is inside the buffer and 1 if it is outside. The problem is that the bc is SpatialPolygons and it doesn't contain the attribute table.


Obviously to add a column to a SpatialPolygon object you have to convert it to a SpatialPolygonsDataFrame, but I don't know how.


I tried this:


buf_df<-as.data.frame(bc)

s_po<-SpatialPolygonsDataFrame(bc,buf_df)
s_po$ratings=0

but this error pops up:


row.names of data and Polygons IDs do not match 


No comments:

Post a Comment