使用substitute()获取参数名称,多个级别

wch*_*wch 6 r

考虑这个函数a(),它打印出传入的参数:

a <- function(x) {
  message("The input is ", deparse(substitute(x)))
}

a("foo")
# The input is "foo"

tmplist <- list(x1 = 1, x2=2)
a(tmplist)
# The input is tmplist
Run Code Online (Sandbox Code Playgroud)

这样可行.但是当a()从另一个函数调用时,它不再打印出原始的参数名称:

b <- function(y) {
  a(y)
}

b("foo")
# The input is y

b(tmplist)
# The input is y
Run Code Online (Sandbox Code Playgroud)

一个似乎有用的解决方案是包装另一个substitute和一个eval:

a1 <- function(x) {
  message("The input is ", deparse(eval(substitute(substitute(x)), parent.frame())))
}

a1("foo")
# The input is "foo"

tmplist <- list(x1 = 1, x2=2)
a1(tmplist)
# The input is tmplist

b1 <- function(y) {
  a1(y)
}

b1("foo")
# The input is "foo"

b1(tmplist)
# The input is tmplist
Run Code Online (Sandbox Code Playgroud)

但这似乎不够优雅.如果我添加另一层,它会失败:

c1 <- function(z) {
  b1(z)
}
c1("foo")
# The input is z
Run Code Online (Sandbox Code Playgroud)

获得原始论证是否有一种好的,通用的方法?

koh*_*ske 3

我不确定这是否在所有情况下都能正常工作,但请尝试以下操作:

f0 <- function(x) {
  nn <- substitute(x)
  i <- 1
  while(TRUE) {
    on <- do.call("substitute", list(as.name(nn), parent.frame(i)))
    if (on == nn) break;
    nn <- on
    i <- i + 1
  }
  message("The input is ", nn)
}

f1 <-function(.f1) f0(.f1)
f2 <- function(.f2) f1(.f2)
Run Code Online (Sandbox Code Playgroud)

进而,

> f2(foo)
The input is foo
> f1(poo)
The input is poo
> f0(moo)
The input is moo
> f2(";(")
The input is ;(
> f1(":)")
The input is :)
> f0(":p")
The input is :p
Run Code Online (Sandbox Code Playgroud)