考慮這個功能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()
從另一個函數調用,它不再打印出原來的參數名:
substitute
包裹
b <- function(y) {
a(y)
}
b("foo")
# The input is y
b(tmplist)
# The input is y
一種解決方案和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'來玩kohske,或者指定一個全局變量是唯一的選擇。 R不會像c那樣通過引用傳遞。 –