假设我有一个函数,我想稍微调整一下行为(比如跳过某一行)。我可以
debug
以交互方式更改代码。trace
注入自己的代码。我只对这篇文章的选项3感兴趣。
例如,让我们假设以下非常简单的代码:
f <- function(dbg) {
x <- rnorm(1)
if (dbg) {
cat("Message 1\n")
}
if (x < 0 & dbg) {
cat("Message 2\n")
}
x
}
如果(无论出于何种原因)我想跳过
Message 2
(但保留Message 1
)我可以使用trace
如下:
set.seed(12231)
untrace(f)
f(TRUE)
# Message 1
# Message 2
# [1] -0.5787277
trace(f, quote(dbg <- FALSE), at = 4, print = FALSE)
set.seed(12231)
f(TRUE)
# Message 1
# [1] -0.5787277
现在假设一个稍微不同的函数
g
:
g <- function() {
x <- rnorm(1)
cat("Message\n")
cat("Message 2\n")
x
}
概念上我想做这样的事情:
trace(g, quote(if(FALSE)), at = 4, print = FALSE)
但这显然不起作用。
有没有办法我可以使用
trace
跳过(a)某些行?或者是我复制、粘贴和编辑功能的唯一选择?
像这样重新定义
cat
。如果您不想要 print=FALSE
消息,请在问题中添加 Tracing
参数。
trace(g, quote(cat <- list), at = 4)
## [1] "g"
g()
## Message
## Tracing g() step 4
## [1] 0.6007088
或者像这样:
trace(g, quote(cat <- function(x, ...) if (x != "Message 2\n") base::cat(x, ...)))
## [1] "g"
g()
## Tracing g() on entry
## Message
## [1] 1.997213