在R中调试意外错误-如何找到错误发生的地方? [英] Debugging unexpected errors in R -- how can I find where the error occurred?

查看:467
本文介绍了在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行给出了错误.很清楚现在,我们可以重新分配f并将browser放置在f2调用之前,以检查其输入. browser()只是允许您停止执行功能并在其环境中环顾四周.与debugdebugonce相似,不同之处在于您不必执行每一行,直到知道问题出了点为止.

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天全站免登陆