使用substitute来获取参数名称

dar*_*een 31 r

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

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]]
Run Code Online (Sandbox Code Playgroud)

Rei*_*son 62

这里的规范成语是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"
Run Code Online (Sandbox Code Playgroud)


Mar*_*rek 23

我会去

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

然后

foo(x,y,z)
# [1] "y" "z"
Run Code Online (Sandbox Code Playgroud)

相关问题之前是关于StackOverflow: 如何在编写自己的函数时使用R的省略号功能?值得阅读.


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

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