Sometimes R throws me errors such as
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?
Since most packages come compressed, it isn't trivial to grep /usr/lib/R/library
.
Just to add to what @SachaEpskamp has already suggested, setting
options(error=recover)
andoptions(show.error.locations=TRUE)
can be extremely helpful when debugging unfamiliar code. The first causes R to launch a debugging session on error, giving you the option to invoke the browser at any point in the call stack up to that error. The second option will tell R to include the source line number in the error.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 putbrowser()
at that point, run the function again and see what is going wrong.For example, here are two functions:
Note that
f2()
assumes an argument of length1
. We can misusef
:Now we can use
traceback()
to locate what went wrong:The number means how deep we are in the nested functions. So we see that
f
callsf2
and that gives an error at line3
. Pretty clear. We could reassignf
withbrowser
placed just before thef2
call now to check it's input.browser()
simply allows you to stop executing a function and look around in its environment. Similar todebug
anddebugonce
except that you don't have to execute every line up until the point you know something goes wrong.