object - Convert any R variable's value to string -


coming java/scala, have been trying figure out how convert value string equivalent.

essentially, take output see in r repl , use string.

myfunc <- function(x) { x + 1} myfunc #function(x) { x + 1} 

other cases sparkr:

sc #java ref type org.apache.spark.api.java.javasparkcontext id 0 

i've tried using options tostring() , as.character(), both fail:

tostring(myfunc) #error in paste(x, collapse = ", ") : #  cannot coerce type 'closure' vector of type 'character'  tostring(sc) #error in as.vector(x, "character") : #  cannot coerce type 'environment' vector of type 'character' 

i can hack this:

rawstring <- function(obj) {   tmp <- "/tmp/rawstring.txt"   if (file.exists(tmp)) file.remove(tmp)   sink(tmp)   print(obj)   sink()   datastring <- paste(readlines(tmp))   if (file.exists(tmp)) file.remove(tmp)   trimws(datastring) } function(obj) {   tmp <- "/tmp/rawstring.txt"   if (file.exists(tmp)) file.remove(tmp)   sink(tmp)   print(obj)   sink()   datastring <- paste(readlines(tmp))   if (file.exists(tmp)) file.remove(tmp)   trimws(datastring) }   rawstring(sc) #[1] "java ref type org.apache.spark.api.java.javasparkcontext id 0"  rawstring(myfunc) #[1] "function(x) { x + 1}" 

but, avoid writing , reading files and relying on sink(). there way string representation repl prints out?

try capture.output. it's rawstring, built in.

capture.output(myfunc) [1] "function(x) { x + 1}" 

unfortunately can't speak sparktable don't have it.

you might consider ?dput, way provide users copy-paste consoles recreate variable, though doesn't convert string (e.g. dput(iris) --> if copy-paste terminal i'd got).


Comments