向上移动框架,调试R环境 [英] move up a frame, debug R environment
问题描述
在调试函数时,我想移至父框架并查看那里的一些变量。我该怎么做?
When debugging a function, I would like to move up to the parent frame and look at some variables there. How do I do this?
这里是一个示例:
f <- function() {
x <-1
g(x+1)
}
g <- function(z) {
y = z+2
return(y)
}
然后我使用<$调试这两个函数c $ c> debug( g)和 debug( f)
。当我在 Browser>
遇到 g
时,我想返回到 f
检查x。
I then debug both functions using debug("g")
and debug("f")
. When I end up in g
at the Browser>
, I would like to move back up to f
to examine x.
谢谢
推荐答案
在R术语中,您想调查 g()
的评估环境(即调用 g
的环境)的父框架。 ?sys.parent
的帮助页中记录了执行该操作的功能。
In R terminology, you are wanting to investigate the parent frame of g()
's evaluation environment (i.e. the environment in which g
was called). The functions for doing that are documented in the help page for ?sys.parent
.
一旦浏览器指示您正在'调试g(x + 1)'
,则可以执行以下操作。 (感谢Joshua Ulrich建议使用 where
来帮助定位呼叫堆栈中的位置。)
Once your browser indicates that you are 'debugging in g(x + 1)'
, you can do the following. (Thanks to Joshua Ulrich for suggesting where
to help locate ones position in the call stack .)
# 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
编辑:要了解?sys.parent
中描述的功能集合,可能值得注意的是 parent.frame()
(基本上)是 sys.frame(sys.parent(1))
的简写。如果您发现自己位于调用堆栈下方的评估环境中(例如 where
所示),则可以进入备份堆栈更远的环境(例如两个通过 parent.frame(2)
或 sys.frame(sys.parent(2))
进行下一步)。
EDIT: To understand the collection of functions described in ?sys.parent
, it's probably worth noting that parent.frame()
is (basically) shorthand for sys.frame(sys.parent(1))
. If you find yourself in an evaluation environment farther down a call stack (as revealed by where
, for instance), you can reach into environments farther back up the call stack (say two steps up) by either parent.frame(2)
or sys.frame(sys.parent(2))
.
这篇关于向上移动框架,调试R环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!