Ale*_*lex 1 browser debugging r
我有一个R脚本,我插入了以下代码:
options(Debug=TRUE)
#SOME MORE CODE
browser(expr = isTRUE(getOption("Debug")))
#SOME MORE CODE
Run Code Online (Sandbox Code Playgroud)
调试器启动后,我希望它继续下一行,所以我输入n.然而,这并没有进入下一行,而是似乎继续.
如何在browser()声明后逐步完成代码的其余部分?
谢谢
要在函数中设置开始调试的点,您可能想要使用trace().
假设您有一个函数,myFun并希望在调用之前开始调试它plot():
myFun <- function() {
x <-
8:1
y <-
1:8
plot(y~x)
lines(y~x)
text(x,y, letters[1:8], pos=3)
}
Run Code Online (Sandbox Code Playgroud)
为了构建呼叫trace,您需要知道在哪个步骤在myFun调用plot()发生.要确定的是,使用结构as.list(body(myFun)):
as.list(body(myFun))
# [[1]]
# `{`
#
# [[2]]
# x <- 8:1
#
# [[3]]
# y <- 1:8
#
# [[4]]
# plot(y ~ x)
#
# ... More ...
Run Code Online (Sandbox Code Playgroud)
在注意到在步骤4中调用绘图之后,您可以使用trace()告诉R您每次myFun调用时都希望在步骤4之前进入浏览器:
trace(myFun, browser, 4)
# TRY IT OUT
# (Once in the browser, type "n" and press Enter to step through the code.)
myFun()
Run Code Online (Sandbox Code Playgroud)
最后,当您完成调试功能后,通过调用关闭轨迹untrace(myFun).
编辑:为源代码脚本设置断点的策略类似.同样,您实际上并未在脚本中插入代码.而是使用findLineNum()和setBreakPoint().
假设上述函数myFun()在文本文件中定义,"myScript.R"该函数在函数定义之前有五个空行.要在调用plot之前插入断点:
source("myScript.R") # Must source() once before using findLineNum
# or setBreakPoint
findLineNum("myScript.R#10") # I see that I missed the step by one line
setBreakpoint("myScript.R#11") # Insert the breakpoint at the line that calls
# plot()
myFun() # Test that breakpoint was properly inserted
# (Again, use "n" and Enter to step through code)
Run Code Online (Sandbox Code Playgroud)