Is there a practical way to dput()
an sp
object in R?
When I try to do the following:
data(World, package = "tmap")
dput(World[1:10, ], file=(tempFile <- tempfile()))
World2 <- dget(tempFile)
I get:
> World2 <- dget(tempFile)
Error in parse(file = file, keep.source = keep.source) :
...\file14f4ee257b1:155:23: unexpected '<'
154: 9L, 10L, 12L, 14L, 16L, 17L), class = "data.frame")
155: , polygons = list(<
^
The <
is usually followed by S4 object of class structure("Polygons", package = "sp")>
, so dput()
apparently does not resolve these nested S4 objects.
The problem seems to be quite similar to this one, but the proposed solution does not work here.
For a solution, please assume that I do not have access to the file system.
EDIT: The more general question is, of course: How can I send a complete sp
object to the console?
Despite the comments suggests to save the
sp
Object as.rds
-file (which is probably for the best when saving things for yourself), sometimes it is more preferable to get a text-version of the object. In fact, when providing a reproducible example for SO/SX Qs it is more handy to provide data in text form. Moreover, as stated in the question, there might be cases in which you cannot access the file system.If you just want to share a
sp
object's coordinates you can usergeos::writeWKT()
This can then be inserted into your example like:
Unfortunately, thus the attribute information (
x@data
) and CRS are lost. Thus, one must consider adding this information if needed by addingdput(x@data)
to create aSpatial*DataFrame
.