13

I'm using gSimplify (rgeos package) to simplify the geometries of a shapefile. The funcion works good, but now I can't write the output in a new shapefile. I tried some ways:

writeOGR(simplyshape, file, driver="ESRI Shapefile", layer='test')

I get

obj must be a SpatialPointsDataFrame, SpatialLinesDataFrame or SpatialPolygonsDataFrame

and with:

writePolyShape(simplyshape, file)

I get:

Error: is(x, "SpatialPolygonsDataFrame") is not TRUE

2 Answers 2

11

Coerce your object to the appropriate Spatial*DataFrame-class (Points/Lines/Polygons), e.g. for SpatialPolygons using as(x, "SpatialPolygonsDataFrame" ):

R> l <- readWKT("LINESTRING(0 7,1 6,2 1,3 4,4 1,5 7,6 6,7 4,8 6,9 4)")
R> x1 <- gSimplify(p, tol=10)
R> class(x1)
[1] "SpatialPolygons"
attr(,"package")
[1] "sp"
R> x2 <- as(x, "SpatialPolygonsDataFrame")
R> class(x2)
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"
6

You need to convert your SpatialPolygons class to a SpatialPolygonsDataFrame class. For example:

require(rgdal)
require(rgeos)

# Read shapefile
shp = 'C:/temp/myshp.shp'
myshp = readOGR(shp, layer = basename(strsplit(shp, "\\.")[[1]])[1])

# Read shapefile attributes
df = data.frame(myshp)

# Simplify geometry using rgeos
simplified = gSimplify(myshp, tol = 1000, topologyPreserve=FALSE)

# Create a spatial polygon data frame (includes shp attributes)
spdf = SpatialPolygonsDataFrame(simplified, df)

# Write to shapefile
writeOGR(spdf, layer = 'myshp_simplified', 'C:/temp', driver="ESRI Shapefile")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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