Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit and debug R library sources

Tags:

r

I've included a library called blotter in my R script which has a bug in it. Is there an easy way for me to edit the source to try and debug the issue?

like image 288
Ben McCann Avatar asked Aug 02 '10 02:08

Ben McCann


People also ask

How do I debug in R?

If you have the . R file corresponding to the code you want to debug, it's easy to use editor breakpoints or browser() to add breakpoints to it. Sometimes, however, you don't have the source file for the code you want to debug. When this is the case, you can set a debug flag on the function you want to debug.

How do I change the source code in R?

R code to make the changes I need? You can get the function code with getAnywhere(generic_RShiny) . To edit it, you could paste it into a R script file, make your edits, assign it to a new object (like my_generic_RShiny ) then run your new version of the function.

How do I trace an error in R?

R provides a number of tools for debugging: traceback() debug() browser() trace() recover() 140.776 Statistical Computing R: Debugging Page 3 traceback() When an R function fails, an error is printed to the screen. Immediately after the error, you can call traceback() to see in which function the error occurred.

What are the tools for debugging in R?

The built-in debugging tools (programs: functions) in R statistical computing environment are traceback(), debu(), browser(), trace(), and recover().


2 Answers

Look up the trace and browser functions, they are the basic tools in R for debugging. Say you want to edit the source of function foo, then saying

trace("foo",edit=TRUE)

will open up the source of foo in the editor for you to change. However, this is for interactive debugging; the source files in the packages are not changed. So once you have found the bug, you need to change the package source files for the change to be permanent.

like image 71
Jyotirmoy Bhattacharya Avatar answered Nov 03 '22 19:11

Jyotirmoy Bhattacharya


Such a feature is implemented in the development version of R (Jul 16, 2010):

A new facility has been added to r-devel for experimenting by authors of packages.

The idea is to insert modified code from the package source into the running package without re-installing. So one can change, test, change, etc in a quick loop.

The mechanism is to evaluate some files of source code, returning an environment object which is a snapshot of the code. From this environment, functions and methods can be inserted into the environment of the package in the current session. The insertion uses the trace() mechanism, so the original code can be restored.

The one-step version is:

insertSource("mySourceFile.R", package = "myPackage", functions = "foo")

See this post for further details: Inserting and testing revised functions in a package

like image 23
rcs Avatar answered Nov 03 '22 18:11

rcs