我有以下代码:
abc <- function() {
def <- function() { }
def_enter <- function() { print("def_enter") }
def_exit <- function() { print("def_exit") }
trace(def, def_enter, exit = def_exit)
def()
}
abc_enter <- function() { print("abc_enter") }
abc_exit <- function() { print("abc_exit") }
trace(abc, abc_enter, exit = abc_exit)
abc()
我希望输出像这样:
> abc()
Tracing abc() on entry
[1] "abc_enter"
Tracing def() on entry
[1] "def_enter"
Tracing def() on exit
[1] "def_exit"
Tracing abc() on exit
[1] "abc_exit"
NULL
但得到这样的输出:
> abc()
Tracing abc() on entry
[1] "abc_enter"
Tracing function "def" in package "base"
Tracing abc() on exit
[1] "abc_exit"
NULL
是否有可能获得我期望的输出?我如何修复上面的代码?
答案 0 :(得分:3)
您需要指定调用trace
中函数的环境。
只需在where
的定义中的跟踪abc
中提及它:
abc <- function() {
def <- function() { }
def_enter <- function() { print("def_enter") }
def_exit <- function() { print("def_exit") }
trace(def, def_enter, exit = def_exit, where=environment())
def()
}
通过致电abc
,您将获得预期的结果:
#>abc()
#Tracing abc() on entry
#[1] "abc_enter"
#Tracing function "def" in package ".GlobalEnv"
#Tracing def() on entry
#[1] "def_enter"
#Tracing def() on exit
#[1] "def_exit"
#Tracing abc() on exit
#[1] "abc_exit"
#NULL