如何找到发生R错误的地方? [英] How to find where an R error occurred?

查看:96
本文介绍了如何找到发生R错误的地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候R会抛出错误,如

Sometimes R throws me errors such as


if(ncol(x)!= 2){当我没有写这样的代码时,没有其他信息,零

Error in if (ncol(x) != 2) { : argument is of length zero

有没有一个通用的方式来查找哪个函数导致错误?

with no additional information, when I've written no such code. Is there a general way for finding which function in which package causes an error?

由于大多数程序包都被压缩,所以grep不是很简单 / usr / lib / R / library

Since most packages come compressed, it isn't trivial to grep /usr/lib/R/library.

推荐答案

可以使用 traceback()来定位最后一个错误发生的位置。通常它会指向你在你的功能中的一个电话。那么我通常会把 browser()再次运行,看看出了什么问题。

You can use traceback() to locate where the last error occurred. Usually it will point you to a call you make in your function. Then I typically put browser() at that point, run the function again and see what is going wrong.

例如,这里有两个功能:

For example, here are two functions:

f2 <- function(x)
{
  if (x==1) "foo"
}

f <- function(x)
{
  f2(x)
}

请注意, f2()假定长度 1 。我们可以滥用 f

Note that f2() assumes an argument of length 1. We can misuse f:

> f(NULL)
Error in if (x == 1) "foo" : argument is of length zero

现在我们可以使用 traceback()来找出出了什么问题:

Now we can use traceback() to locate what went wrong:

> traceback()
2: f2(x) at #3
1: f(NULL)

数字表示我们在嵌套函数中有多深。因此,我们看到 f 调用 f2 ,并且在 3 。很清楚我们可以在 f2之前放置浏览器现在打电话来检查它的输入。 browser()只需允许您停止执行一个功能并在其环境中环顾四周。类似于 debug debugonce ,除了你不必执行每一行,直到你知道某事

The number means how deep we are in the nested functions. So we see that f calls f2 and that gives an error at line 3. Pretty clear. We could reassign f with browser placed just before the f2 call now to check it's input. browser() simply allows you to stop executing a function and look around in its environment. Similar to debug and debugonce except that you don't have to execute every line up until the point you know something goes wrong.

这篇关于如何找到发生R错误的地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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