考虑这个函数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
有没有一种好的、普遍的方法来获取原始参数?
parent.frame
,要么指定一个全局变量是你唯一的选择。R不像C那样通过引用传递。 - Carl Witthoft