如何在 RStudio 中为包函数设置断点

How to set breakpoints for package functions in RStudio

要重现此错误,您必须先安装软件包 MARSS。我还附上了用户指南。

https://cran.r-project.org/web/packages/MARSS/vignettes/UserGuide.pdf

可以使用

调用第 35 页上的示例
dat = t(harborSealWA)
dat = dat[2:nrow(dat),]
debugonce(MARSSkem)
kemfit = MARSS(dat)

在RStudio中为MARSSkem触发debugmode时,你会发现无法设置断点!屏幕顶部还有一条调试消息:"Debug location is approximate because source source code is not available"。我想这就是我无法设置断点的原因!

问题是我试图定位的错误(在所示的简单示例中不存在)是在第 55 次迭代时发现的,每次迭代都包含几个 for 循环,每个循环有 100 个循环!手动一步根本不实用!

Q1.) 有没有办法在R studio中为这个函数设置断点?

Q2.) 如果不是,我找到这个问题的最佳选择是什么? (理想情况下,我不想乱搞包源代码,但如果这是唯一的选择,我会的)

谢谢

巴兹

最简单的方法(我认为)是制作您自己的函数副本,获取它的源代码,然后使用断点。

为此:

View(MARSS)

您应该会看到源弹出窗口。现在将其复制粘贴到一个开头带有 mymarss <- 的新脚本中,保存它(可能是 mymarss.R),然后获取它。

source(mymarss.R)

现在你可以正常调试了:

dat = t(harborSealWA)
dat = dat[2:nrow(dat),]
debugonce(mymarss)
kemfit = mymarss(dat)

而且你可以自由add/Remove断点等等

来自Debugging with RStudio

Breakpoints can be set in package code just as they can in free-standing R code. The primary difference is that you’ll need to have an up-to-date build of your package in order to set breakpoints. If your package build isn’t up to date, RStudio will warn you when you try to set a breakpoint.

In order to debug effectively in your package, you’ll also want to ensure that your package is compiled with the --with-keep.source option. This option is the default for new packages in RStudio; if you need to set it manually, it can be found in Tools -> Project Options -> Build Tools.

When a breakpoint is set in a file inside a package, RStudio will automatically disable the breakpoint when the package is unloaded and enable the breakpoint when the package is loaded. If you’re having trouble setting breakpoints in a package, make sure that the package was compiled with source information as described above and that its build is up-to-date.

我认为这不适用于 R 会话。如果要调试调用包函数的代码,需要在与调用代码相同的会话中打开包含函数的包文件,然后在封装函数.