将任何 R 变量的值转换为字符串 [英] Convert any R variable's value to string

查看:57
本文介绍了将任何 R 变量的值转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Coming from Java/Scala, I have been trying to figure out how to convert any value to a string equivalent.

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

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}

其他情况与 SparkR 类似:

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

我尝试过使用 toString()as.character() 之类的选项,但它们都失败了:

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'

我可以这样做:

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 打印出来的字符串表示?

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?

推荐答案

尝试 capture.output.它本质上是您的 rawString,但已内置.

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

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

不幸的是,我不能代表 sparkTable,因为我没有它.

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

您也可以考虑使用 ?dput,这是一种很好的方式,可以为用户提供一些内容以将其复制粘贴到他们的控制台中以重新创建您的变量,但不会转换为字符串(例如 dput(iris) --> 如果我将它复制粘贴到我的终端中,我会得到你所得到的.

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).

这篇关于将任何 R 变量的值转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆