如何在该非匿名函数中获取函数的名称?下面我假设有一个函数或过程来执行此调用magical_r_function()以及预期的输出是什么。
my_fun <- function(){
magical_r_function()
}
my_fun()
## [1] "my_fun"
foo_bar <- function(){
magical_r_function()
}
foo_bar()
## [1] "foo_bar"
ballyhoo <- function(){
foo_bar()
}
ballyhoo()
## [1] "foo_bar"
tom_foolery <- foo_bar
tom_foolery()
## [1] "tom_foolery"
Run Code Online (Sandbox Code Playgroud)
r2e*_*ans 21
as.character(match.call()[[1]])
Run Code Online (Sandbox Code Playgroud)
演示:
my_fun <- function(){
as.character(match.call()[[1]])
}
my_fun()
# [1] "my_fun"
foo_bar <- function(){
as.character(match.call()[[1]])
}
foo_bar()
# [1] "foo_bar"
ballyhoo <- function(){
foo_bar()
}
ballyhoo()
# [1] "foo_bar"
tom_foolery <- foo_bar
tom_foolery()
# [1] "tom_foolery"
Run Code Online (Sandbox Code Playgroud)
G. *_*eck 12
尝试sys.call(0)调用对象输出是否正常,或者如果您只想将名称作为字符串进行解析。以下是对此的一些测试。sys.call 返回名称和参数,而 [[1]] 只选择名称。
my_fun <- function() deparse(sys.call(0)[[1]])
g <- function() my_fun()
my_fun()
## [1] "my_fun"
g()
## [1] "my_fun"
Run Code Online (Sandbox Code Playgroud)
请注意,函数实际上没有名称。我们认为的函数名实际上只是保存函数的变量,而不是函数本身的一部分。函数由参数、主体和环境组成——在这些成分中没有函数名称。
此外,可以有匿名函数,当与上述函数一起使用时,这些函数可能会返回奇怪的结果。
sapply(1:3, function(x) deparse(sys.call(0)[[1]]))
## [1] "FUN" "FUN" "FUN"
Run Code Online (Sandbox Code Playgroud)
确实存在一些情况,特别是涉及匿名函数的情况,其中deparse将返回多个元素,因此如果您想涵盖此类边缘情况,请使用 nlines = 1 参数来解析或使用 deparse(...)[[1]] 或作为@Konrad Rudolph 在 R 4.0.0 中使用 deparse1 提到。
Map(function(x) deparse(sys.call(0)[[1]], nlines = 1), 1:2)
## [[1]]
## [1] "function (x) "
##
## [[2]]
## [1] "function (x) "
Map(function(x) deparse(sys.call(0)[[1]]), 1:2) # without nlines=1
## [[1]]
## [1] "function (x) " "deparse(sys.call(0)[[1]])"
##
## [[2]]
## [1] "function (x) " "deparse(sys.call(0)[[1]])"
Run Code Online (Sandbox Code Playgroud)
回想一下。如果您想要函数名称的原因是递归调用该函数,请Recall()改用。从帮助文件:
fib <- function(n)
if(n<=2) { if(n>=0) 1 else 0 } else Recall(n-1) + Recall(n-2)
fib(4)
## [1] 3
Run Code Online (Sandbox Code Playgroud)
警告和停止它们都会发出函数的名称以及传递给它们的任何参数,因此无需获取当前的函数名称。
testWarning <- function() warning("X")
testWarning()
## Warning message:
## In testWarning() : X
Run Code Online (Sandbox Code Playgroud)
我们也可以使用
my_fun <- function(){
as.character(as.list(sys.calls()[[1]])[[1]])
}
my_fun()
#[1] "my_fun"
Run Code Online (Sandbox Code Playgroud)