【问题标题】:using substitute to get argument name with使用替换来获取参数名称
【发布时间】:2011-04-22 10:06:45
【问题描述】:

我正在尝试在函数中获取全局环境中的参数名称。我知道我可以使用替代来获取命名参数的名称,但我希望能够用 ... 参数做同样的事情。我有点让它为...的第一个元素工作,但不知道如何为其余元素做它。知道如何让它按预期工作。

foo <- function(a,...)
{
    print(substitute(a))
    print(eval(enquote(substitute(...))))
    print(sapply(list(...),function(x) eval(enquote(substitute(x)),env=.GlobalEnv)))
}

x <- 1
y <- 2
z <- 3
foo(x,y,z)

x
y
[[1]]
X[[1L]]

[[2]]
X[[2L]]

【问题讨论】:

    标签: r


    【解决方案1】:

    这里的规范成语是deparse(substitute(foo)),但... 需要稍微不同的处理。这是一个可以满足您要求的修改:

    foo <- function(a, ...) {
        arg <- deparse(substitute(a))
        dots <- substitute(list(...))[-1]
        c(arg, sapply(dots, deparse))
    }
    
    x <- 1
    y <- 2
    z <- 3
    
    > foo(x,y,z)
    [1] "x" "y" "z"
    

    【讨论】:

      【解决方案2】:

      我会去

      foo <- function(a, ...) {
      print( n <- sapply(as.list(substitute(list(...)))[-1L], deparse) )
          n
      }
      

      然后

      foo(x,y,z)
      # [1] "y" "z"
      

      相关问题以前在 StackOverflow 上: How to use R's ellipsis feature when writing your own function? 值得一读。


      第二种解决方案,使用match.call

      foo <- function(a, ...) {
          sapply(match.call(expand.dots=TRUE)[-1], deparse)
      }
      

      【讨论】:

      • 很好地使用了match.call() - 我不知道expand.dots 参数。
      • 迟到了,但names(sapply(match.call(), deparse))[-1] 为我获取参数名称的字符向量的用例工作([-1] 删除了函数名称本身)
      猜你喜欢
      • 1970-01-01
      • 2023-01-18
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      相关资源
      最近更新 更多