dput() sp object in R

176 views Asked by At

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?

1

There are 1 answers

0
loki On

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 use rgeos::writeWKT()

library(rgeos)
writeWKT(x)
# [1] "POLYGON ((1441727.5096940901130438 6550163.0046194596216083, 
#                 1150685.2609429201111197 6669225.7427449300885201, 
#                 975398.4520359700545669 6603079.7771196700632572, 
#                 866257.6087542800232768 6401334.5819626096636057, 
#                 1441727.5096940901130438 6550163.0046194596216083))"

This can then be inserted into your example like:

library(rgeos)
x <- readwkt("POLYGON ((1441727.5096940901130438 6550163.0046194596216083, 
                        1150685.2609429201111197 6669225.7427449300885201, 
                        975398.4520359700545669 6603079.7771196700632572, 
                        866257.6087542800232768 6401334.5819626096636057, 
                        1441727.5096940901130438 6550163.0046194596216083))")

Unfortunately, thus the attribute information (x@data) and CRS are lost. Thus, one must consider adding this information if needed by adding dput(x@data) to create a Spatial*DataFrame.