Question

I occasionally find that it would be useful to get the printed representation of an R object as a character string, like Python's repr function or Lisp's prin1-to-string. Does such a function exist in R? I don't need it to work on complicated or weird objects, just simple vectors and lists.

Edit: I want the string that I would have to type into the console to generate an identical object, not the output of print(object).

Was it helpful?

Solution

I'm not familiar with the Python/Lisp functions you listed, but I think you want either dput or dump.

x <- data.frame(1:10)
dput(x)
dump("x", file="clipboard")

OTHER TIPS

See ?evaluate in the evaluate package.

EDIT: Poster later clarified in comments that he wanted commands that would reconstruct the object rather than a string that held the print(object) output. In that case evaluate is not what is wanted but dput (as already mentioned by Joshua Ullrich in comments and since I posted has been transferred to an answer) and dump will work. recordPlot and replayPlot will store and replot classic graphics on at least Windows. trellis.last.object will retrieve the last lattice graphics object. Also note that .Last.value holds the very last value at the interactive console.

You can use capture.output:

repr <- function(x) {
  paste(sprintf('%s\n', capture.output(show(x))), collapse='')
}

For a version without the line numbers something along these lines should work:

repr <- function(x) {
  cat(sprintf('%s\n', capture.output(show(x))), collapse='')
}

I had exactly the same question. I was wondering if something was built-in for this or if I would need to write it myself. I didn't find anything built-in so I wrote the following functions:

dputToString <- function (obj) {
  con <- textConnection(NULL,open="w")
  tryCatch({dput(obj,con);
           textConnectionValue(con)},
           finally=close(con))
}

dgetFromString <- function (str) {
  con <- textConnection(str,open="r")
  tryCatch(dget(con), finally=close(con))
}

I think this does what you want. Here is a test:

> rep <- dputToString(matrix(1:10,2,5))
> rep
[1] "structure(1:10, .Dim = c(2L, 5L))"
> mat <- dgetFromString(rep)
> mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top