在 R 中发生错误后获取变量的状态 [英] Getting the state of variables after an error occurs in R

查看:21
本文介绍了在 R 中发生错误后获取变量的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我刚刚调用了一个函数 f,并且在该函数的某处发生了错误.我只是希望能够在错误发生之前检查不同变量的值.

Let's say I have just called a function, f, and an error occurred somewhere in the function. I just want to be able to check out the values of different variables right before the error occurred.

假设我的直觉告诉我这是一个小错误,所以我懒得使用 debug(f) 并且懒得将 browser() 插入到零件中我认为事情出错的功能.而且我懒得开始放入 print() 语句.

Suppose my gut tells me it's a small bug, so I'm too lazy to use debug(f) and too lazy to insert browser() into the part of the function where I think things are going wrong. And I'm far too lazy to start putting in print() statements.

这是一个例子:

x <- 1:5
y <- x + rnorm(length(x),0,1)
f <- function(x,y) {
  y <- c(y,1)
  lm(y~x)
}

调用 f(x,y) 我们得到以下错误:

Calling f(x,y) we get the following error:

Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'x')

在这个例子中,我想在调用 lm() 之前获取环境的状态;这样我就可以调用 xy 并看到它们的长度不同.(这个例子可能太简单了,但我希望它能让你明白.)

In this example, I want grab the state of the environment just before lm() is called; that way I can call x and y and see that their lengths are different. (This example may be too simple, but I hope it gets the idea across.)

推荐答案

正如所指出的 这里,有一个简单的方法可以做到这一点,我认为这个技巧有可能让生活变得更好.

As pointed out here, there's an easy way to do this, and I think this trick has the potential to change lives for the better.

首先,调用这个:

options(error=recover)

现在,当我们调用 f(x,y) 时,我们将可以选择要恢复的环境.在这里,我选择了选项 1,它会打开一个调试器,让我在调用 lm() 之前处理变量.

Now when we call f(x,y) we will have an option to choose an environment to recover. Here I select option 1, which opens up a debugger and lets me play around with variables just before lm() is called.

> f(x,y)
Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'x')

Enter a frame number, or 0 to exit   

1: f(x, y)
2: lm(y ~ x)
3: eval(mf, parent.frame())
4: eval(expr, envir, enclos)
5: model.frame(formula = y ~ x, drop.unused.levels = TRUE)
6: model.frame.default(formula = y ~ x, drop.unused.levels = TRUE)

Selection: 1
Called from: eval(expr, envir, enclos)
Browse[1]> x
[1] 1 2 3 4 5
Browse[1]> y
[1] 1.6591197 0.5939368 4.3371049 4.4754027 5.9862130 1.0000000

这篇关于在 R 中发生错误后获取变量的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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