1

可能重复:
调试 R 的一般建议?

在调试时,我经常想知道一个已完成执行的函数中使用的变量的值。怎样才能做到这一点?

例子:

我有功能:

MyFunction <- function() {
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(mean(x))
}

我想知道存储在x中的值,这些值在函数执行完毕并清理函数环境后对我不可用。

4

4 回答 4

4

你提到了调试,所以我假设脚本后面不需要这些值,你只想检查发生了什么。在那种情况下,我总是做的是使用browser

MyFunction <- function() {
    browser()
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(mean(x))
}

这会将您带入函数范围内的交互式控制台,允许您检查内部发生的情况。

有关 RI 中调试的一般信息,建议使用此 SO 帖子

于 2012-10-06T11:44:39.180 回答
2
MyFunction <- function() {
    x <- rnorm(10) # assign 10 random normal numbers to x
    return(list(x,mean(x)))
}

这将返回一个列表,其中第一个元素是 x,第二个是它的平均值

于 2012-10-06T11:36:41.760 回答
1

你在这里有很多选择。<<-最简单的方法是在分配给 时使用运算符x。这也是最有可能让你陷入困境的。

> test <- function() x <- runif(1)
> x <- NA
> test()
> x
[1] NA
> test <- function() x <<- runif(1)
> test()
> x
[1] 0.7753325

编辑

@PaulHeimstra 指出您希望将其用于调试。以下是一些通用技巧的指针:

在 R 中调试的一般建议

我建议设置options(error=recover)trace()browser().

于 2012-10-06T11:34:04.710 回答
1

There are already some good solutions, I'd like to add one possibility. I emphasize on the fact that you want to know the value of a variable used in a function that has completed executing. So there is maybe no need to assign those values, and you don't want (a priori) to stop execution. The solution is to simply use print. So it is not used by default but only when you want to debug, the option to print or not can be passed as a function argument:

MyFunction <- function(x, y, verbose = FALSE) {
    a <- x * y
    if (verbose) print(a)
    b <- x - y
    if (verbose) print(b)
    return(a * b)
}

In general, you would run your function like this: MyFunction(10, 4) but when you want to see those intermediate results, do MyFunction(10, 4, verbose = TRUE).

于 2012-10-06T12:03:06.400 回答