Does R have the Python equivalent of "repr" (or Lisp "prin1-to-string")?

I sometimes find that it would be useful to get a printed representation of the R object as a character string, such as the Python repr or Lisp prin1-to-string functions. Does such a function exist in R? I don’t have to work on complex or strange objects, just simple vectors and lists.

Edit: I need a line that I would have to enter into the console in order to create an identical object, not print(object) output.

+7
source share
4 answers

I am 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") 
+16
source

See ?evaluate in the evaluation package.

EDIT: The poster later explained in the comments that it needed commands that would restore the object, not a line containing print(object) output. In this case, evaluate is not what is required, but dput (as mentioned in Joshua Ulrich in the comments, and since I posted, the answer was passed) and dump will work. recordPlot and replayPlot will store and replace classic graphics, at least on Windows. trellis.last.object will retrieve the last grid object. Also note that .Last.value contains the last value on the interactive console.

+6
source

You can use capture.output :

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

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

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

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 did not 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 the 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 
+1
source

All Articles