I would like to ask another question, which includes SpatialPolygons. In order to make it reproducible I wanted to use dput()
for the SpatialPolygons object, but its not outputting a reproducible structure.
Why can I use dput()
with SpatialPoints, but not with Lines/SpatialLines, Polygons/SpatialPolygons?
Is the only workaround, to export the coordinates and recreate the SpatialPolygons in the example?
Test Data:
library(sp)
df = data.frame(lon=runif(10, 15,19), lat=runif(10,40,45))
dput(SpatialPoints(coordinates(df)))
dput(Lines(list(Line(coordinates(df))), 1))
dput(SpatialLines(list(Lines(list(Line(coordinates(df))), 1))))
dput(Polygons(list(Polygon(df)), 1))
dput(SpatialPolygons(list(Polygons(list(Polygon(df)), 1))))
dput(SpatialPolygons(list(Polygons(list(Polygon(df)), 1))), control="all")
The dupt2()
method from this answer works for Lines/SpatialLines but not for Polygons/SpatialPolygons, where this error occurs:
Error in validityMethod(object) : object 'Polygons_validate_c' not found
- So how to make a SpatialPolygons-object reproducible?
A workaround would be to convert the objects to simple features and then use dput()
. They can obviously be deparsed.
Example using LINESTRING and POLYGON:
library(sp)
library(sf)
df = data.frame(lon=runif(10, 15,19), lat=runif(10,40,45))
SLi = SpatialLines(list(Lines(list(Line(coordinates(df))), 1)))
SPo = SpatialPolygons(list(Polygons(list(Polygon(df)), 1)))
dput(st_as_sf(SLi))
dput(st_as_sf(SPo))
dput(SpacialLines)
works for me, however, with polygons I get the errorError in validityMethod(object) : object 'Polygons_validate_c' not found
– Mako212lines = list(<S4 object of class structure("Lines", package = "sp")>)
– SeGa?dput
,Deparsing an object is difficult, and not always possible. With the default control, dput() attempts to deparse in a way that is readable, but for more complex or unusual objects (see dump), not likely to be parsed as identical to the original.
– Moody_MudskipperThis is not a good way to transfer objects between R sessions. dump is better, but the function save is designed to be used for transporting R data, and will work with R objects that dput does not handle correctly as well as being much faster.
So maybe usedump
instead ? – Moody_Mudskipper