就像我们可以使用debugonce
而不是debug
/ undebug
那样,最好使用traceonce
函数而不是{ {1}} / trace
。
我们该怎么做?
答案 0 :(得分:0)
这是我想出的:
traceonce <- function(what, tracer, exit, at, print, signature,
where = topenv(parent.frame()), edit = FALSE){
mc <- match.call()
mc[[1]] <- quote(trace)
mc[["exit"]] <-
if (missing(exit)) substitute(quote(eval.parent(quote(untrace(what)))))
else c(as.expression(exit), substitute(eval.parent(quote(untrace(what)))))
eval.parent(mc)
}
我编辑了电话的格式,所以不必处理missing
上的一堆支票,然后编辑电话中的exit
元素(2种情况,是否存在) )添加对给定函数的untrace的调用。
带有exit
参数:
traceonce(head, exit = quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on exit
#> [1] "hello"
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2
没有exit
参数:
traceonce(head, quote({print("hello")}))
#> Tracing function "head" in package "utils"
#> [1] "head"
head(cars,1)
#> Tracing head(cars, 1) on entry
#> [1] "hello"
#> Tracing head(cars, 1) on exit
#> Untracing function "head" in package "utils"
#> speed dist
#> 1 4 2
head(cars,1)
#> speed dist
#> 1 4 2