在 R 中的不同源文件中调试函数 [英] Debugging a function in a different source file in R

查看:30
本文介绍了在 R 中的不同源文件中调试函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 RStudio,我希望能够在特定行停止代码执行.

I'm using RStudio and I want to be able to stop the code execution at a specific line.

函数在第一个脚本文件中定义并从第二个脚本文件中调用.

The functions are defined in the first script file and called from a second.

我使用 source("C:/R/script1.R")

我使用从头到行运行:从第二个脚本开始运行,该脚本具有函数调用,并在第一个脚本中突出显示了函数定义所在的一行.

I used run from beginning to line: where I start running from the second script which has the function calls and have highlighted a line in the first script where the function definitions are.

然后我使用 browser() 查看变量.然而,这并不理想,因为涉及到一些大型矩阵.有没有办法让这些变量出现在 RStudio 的工作区中?

I then use browser() to view the variables. However this is not ideal as there are some large matrices involved. Is there a way to make these variables appear in RStudio's workspace?

此外,当我使用 run from line to end 重新启动时,它仅运行到调用的第一个脚本文件的末尾,它不会返回调用函数并完成第二个文件的运行.

Also when I restart using run from line to end it only runs to the end of the called first script file it does not return to the calling function and complete the running of the second file.

如何在 RStudio 中实现这些目标?

How can I achieve these goals in RStudio?

这里是一个简单的例子,下面的函数加法器是在一个脚本中定义的

OK here is a trivial example the function adder below is defined in one script

adder<-function(a,b) {  
  browser()
  return(a+b)
 }

我调用的是第二个脚本

x=adder(3,4)

在第二个脚本中调用 adder 时,在第一个脚本中启动 browser().从这里我可以使用 get("a") 来获取 a 的值,但是 a 和 b 的值没有出现在 RStudio 的工作区中?

When adder is called in the second script is starts browser() in the first one. From here I can use get("a") to get the value of a, but the values of a and b do not appear in the workspace in RStudio?

在此处的示例中,这并不重要,但是当您有几个大矩阵时,它确实重要.

In the example here it does not really matter but when you have several large matrices it does.

推荐答案

如果您将数据分配到 .GlobalEnv 中,它将显示在 RStudio 的工作区"选项卡中.

If you assign the data, into the .GlobalEnv it will be shown in RStudio's "Workspace" tab.

> adder(3, 4)
Called from: adder(3, 4)
Browse[1]> a
[1] 3
Browse[1]> b
[1] 4
Browse[1]> assign('a', a, pos=.GlobalEnv)
Browse[1]> assign('b', b, pos=.GlobalEnv)
Browse[1]> c
[1] 7
> a
[1] 3
> b
[1] 4

这篇关于在 R 中的不同源文件中调试函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆