【问题标题】:Cast function argument as a character string?将函数参数转换为字符串?
【发布时间】:2010-11-05 17:47:51
【问题描述】:

超级快速的问题...

如何获取某个特定函数的(用户定义的)参数并将其转换为字符串?

如果举个简单的例子,

foo <- function(x) { ... }

我想简单地返回 x 的对象名称。所以,

foo(testing123)

返回 "testing123"(而 testing123 可能只是一些随机数字向量)

抱歉,如果之前有人问过这个问题--搜索过,但找不到!谢谢!!

【问题讨论】:

    标签: r


    【解决方案1】:
    foo <- function(x) deparse(substitute(x))
    

    【讨论】:

      【解决方案2】:

      元答案:如果您知道 R 做了某事并且您想做,请检查源代码。例如,您可能已经发现 plot(foo)ylab 中粘贴了 'foo',因此 plot 可以做到。如何?先看代码:

      > plot
      function (x, y, ...) 
      {
          if (is.function(x) && is.null(attr(x, "class"))) {
              if (missing(y)) 
                  y <- NULL
              hasylab <- function(...) !all(is.na(pmatch(names(list(...)), 
                  "ylab")))
              if (hasylab(...)) 
                  plot.function(x, y, ...)
              else plot.function(x, y, ylab = paste(deparse(substitute(x)), 
                  "(x)"), ...)
          }
          else UseMethod("plot")
      }
      

      还有一些deparse(substitute(x)) 魔法。

      【讨论】:

      • 不确定它是否真的很重要,因为答案本身很好,但plot 看起来不再像这样了
      【解决方案3】:

      哎呀,显然我搜索的不够仔细......

      foo <- function(x) {return(as.character(substitute(x)))}
      

      这很容易......

      【讨论】:

      • 根据 JD 的回答,deparse(substitute(x)) 将是执行此操作的常用方式。在foo(testing * bar) 上将您的版本与 JD 的版本进行比较以了解原因。