Coming from Java/Scala, I have been trying to figure out how to convert any value to a string equivalent.
Essentially, I would like to take the output you see in the R REPL and use that as the string.
myFunc <- function(x) { x + 1}
myFunc
#function(x) { x + 1}
Other cases are like with SparkR:
sc
#Java ref type org.apache.spark.api.java.JavaSparkContext id 0
I've tried using options like toString() and as.character(), but those both fail:
toString(myFunc)
#Error in paste(x, collapse = ", ") :
# cannot coerce type 'closure' to vector of type 'character'
toString(sc)
#Error in as.vector(x, "character") :
# cannot coerce type 'environment' to vector of type 'character'
I can do a hack like 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, I would like to avoid writing to and reading from files and relying on sink(). Is there a way to get a string representation like the REPL prints out?