将任何R变量的值转换为字符串

时间:2015-07-15 04:22:44

标签: r object tostring

来自Java / Scala,我一直试图弄清楚如何将任何值转换为等效的字符串。

基本上,我想获取您在R REPL中看到的输出并将其用作字符串。

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

其他情况与SparkR相似:

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

我尝试过使用toString()as.character()等选项,但这些选项都失败了:

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'

我可以这样做:

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}"

但是,我希望避免写入和读取依赖sink()的文件。有没有办法获得像REPL打印出来的字符串表示?

1 个答案:

答案 0 :(得分:2)

试试capture.output。它基本上是你的rawString,但内置了。

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

不幸的是,我无法代表sparkTable,因为我没有。

您可能还会考虑使用?dput,这是为用户提供复制粘贴到其控制台以重新创建变量的好方法,但不会转换为字符串(例如dput(iris) - - &gt;如果我将它复制粘贴到我的终端,我会得到你所得到的。

相关问题