向上移动一帧,调试R环境

Ale*_*lex 19 debugging r frame

在调试函数时,我想向上移动到父框架并查看那里的一些变量.我该怎么做呢?

这是一个示例:

f <- function() {
   x <-1
   g(x+1)
}
g <- function(z) {
   y = z+2
   return(y)
}
Run Code Online (Sandbox Code Playgroud)

然后我使用debug("g")和调试这两个函数debug("f").当我最终进入gBrowser>,我想回到f检查x.

谢谢

Vin*_*ynd 34

您可以使用recover (它通常用于在实际错误之后调试代码,通过options(error=utils::recover),但可以直接调用它).

> f()
debugging in: g(x + 1)
debug at #1: {
    y = z + 2
    return(y)
}
Browse[2]> ls()
[1] "z"
Browse[2]> recover()

Enter a frame number, or 0 to exit   

1: f()
2: #3: g(x + 1)

Selection: 1
Called from: top level 
Browse[3]> ls()
[1] "x"
Browse[3]> x
[1] 1
Browse[3]> 
Run Code Online (Sandbox Code Playgroud)

  • 很酷.从来没有想到`recover()`可以交互调用.有时候我觉得我应该坐下来看看其他人回答所有的问题,而这种宝石就是为什么. (3认同)

Jos*_*ien 14

在R术语中,您想要研究g()评估环境的父框架(即g调用的环境).执行此操作的功能记录在帮助页面中?sys.parent.

一旦您的浏览器显示您的身份'debugging in g(x + 1)',您就可以执行以下操作.(感谢Joshua Ulrich建议where帮助找到调用堆栈中的位置.)

# Confirm that you are where you think you are
where
# where 1 at #3: g(x + 1)
# where 2: f()

# Get a reference to g()'s parent frame (an environment object)
pframe <- parent.frame()
pframe
# <environment: 0x019b9174>

# Examine the contents of the parent frame
ls(env=pframe)
# [1] "x"

# Get the value of 'x' in the parent frame
get("x", env = pframe)
# [1] 1
Run Code Online (Sandbox Code Playgroud)

编辑:要理解所描述的函数集合,?sys.parent可能值得注意的parent.frame()是(基本上)简写sys.frame(sys.parent(1)).如果您在评估环境越往下调用堆栈(由所揭示发现自己where,例如),你能够到达更远的环境中备份调用堆栈(比如两步高达)的任一parent.frame(2)sys.frame(sys.parent(2)).

  • 在浏览器中键入`where`似乎有助于确定需要返回的帧数. (4认同)