0

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?

1 Answer 1

2

Try capture.output. It's essentially your rawString, but built in.

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

Unfortunately I can't speak for sparkTable as I don't have it.

You might also consider ?dput, which is a good way to provide something for users to copy-paste into their consoles to recreate your variable, though doesn't convert to string (e.g. dput(iris) --> if I were to copy-paste this into my terminal I'd get exactly what you got).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.