考虑这个函数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
这样可行。但是当a()
从另一个函数调用时,它不再打印出原始参数名称:
b <- function(y) {
a(y)
}
b("foo")
# The input is y
b(tmplist)
# The input is y
一种似乎可行的解决方案是包装另一个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
但这似乎不优雅。如果我添加另一层,它会失败:
c1 <- function(z) {
b1(z)
}
c1("foo")
# The input is z
有没有一种好的、通用的方法来获得原始论点?