These web pages describe various issues involved in debugging code written for the open source statistical package R. It is particularly aimed at Windows programmers, but many of the techniques work more widely.
For instructions particular to other platforms, and non-compiler-specific details, see the Writing R Extensions manual in the docs subdirectory of the R installation.
cat()
and print() functions can be called to print values.
You may need to turn off buffering using the menu item Misc|Buffered output (Ctrl-W) or call
flush.console()
to see results immediately.debug(), browser() and trace()
functions?tryCatch help topic
for lots of detail on R's exception handling. The withCallingHandlers() function
gives a flexible way to debug warning and error conditions.
The general syntax is
withCallingHandlers(expr, ...)where the
expr can be any statement or expression (or list of statements
enclosed in braces {}). The ... arguments establish handlers
for whichever conditions you want to catch.
By default, R defines the warning and error conditions,
which are signalled by warning() and stop() respectively.
Users may define their own conditions and signal them using signalCondition();
see its man page for details.
Typical debugging usage to trap on a warning message would be something like this:
> foo <- function(x) {
+ if (x > 0) return("positive")
+ else return("negative")
+ }
>
> foo(1:5)
[1] "positive"
Warning message:
the condition has length > 1 and only the first element will be used in: if (x > 0) return("positive") else return("negative")
Where did that warning come from? Use withCallingHandlers to find out...
> withCallingHandlers(foo(1:5), warning=function(c) recover())
Enter a frame number, or 0 to exit
1: withCallingHandlers(foo(1:5), warning = function(c) recover())
2: foo(1:5)
3: .signalSimpleWarning("the condition has length > 1 and only the first element wi
4: withRestarts({
5: withOneRestart(expr, restarts[[1]])
6: doWithOneRestart(return(expr), restart)
7: function (c)
Selection: 2
Called from: eval(expr, envir, enclos)
Browse[1]> x
[1] 1 2 3 4 5
Browse[1]>
Enter a frame number, or 0 to exit
1: withCallingHandlers(foo(1:5), warning = function(c) recover())
2: foo(1:5)
3: .signalSimpleWarning("the condition has length > 1 and only the first element wi
4: withRestarts({
5: withOneRestart(expr, restarts[[1]])
6: doWithOneRestart(return(expr), restart)
7: function (c)
Selection: 0
[1] "positive"
Warning message:
the condition has length > 1 and only the first element will be used in: if (x > 0) return("positive") else return("negative")
>
make clean make DEBUG=TThis will build R with full source-level debugging information. Then running gdb or Insight as described above will let you debug the R internals.
Detailed information for Borland Delphi is given here.
If you have worked out instructions for other debuggers, please send them to me.
Last modified: Friday, 20-Aug-2010 16:01:52 EDT, by Duncan Murdoch