Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug (placing break point,etc) an installed R package in RStudio?

I need to run a function line-by-line to understand how it works. But the function is part of an installed package and I don't know where R stores the source of the installed packages (say MultiPhen). I am using RStudio 0.98.501 and R 3.0.2 in Ubuntu 12 (64it). Apparently source code of installed packages are not stored, right? Sorry if it is a naive question, I am new to R. If the sources are not stored, is there anyway to re-install a package with source and debug it (basically place a break point).

Thanks,

Kayhan

like image 751
kayhan Avatar asked Feb 24 '14 22:02

kayhan


People also ask

How do I debug a package in R?

Debugging Installed Packages in RSetting options(error = recover) and then going line by line through the code using n. When facing complicated problems, you can have a copy of the function code with you. Entering function name in R console will print out function code that can be copied into the text editor.

How do I enable debugging in R?

c to leave the debug mode and continue with the regular execution of the function. Q to stop debug mode, terminate the function, and return to the R prompt.


1 Answers

Look at trace. Here is an example adding a breakpoint at the fourth statement in the base package function var. Here we ask trace to invoke the function browser at the sixth statement:

> trace(var, browser, at=6)
Tracing function "var" in package "stats"
[1] "var"
> var(1:10)
Tracing var(1:10) step 6 
Called from: eval(expr, envir, enclos)
Browse[1]> n
debug: if (is.data.frame(y)) y <- as.matrix(y) else stopifnot(is.atomic(y))
Browse[2]> n
debug: stopifnot(is.atomic(y))
Browse[2]> n
debug: .Call(C_cov, x, y, na.method, FALSE)
Browse[2]> n
[1] 9.166667

Remember to untrace when you're done. You can do fairly complex stuff with trace, though in most cases trace(fun.name, browser) is probably enough.

Alternatively, you can just load the package and type the name of the function on the command line like so:

> var
function (x, y = NULL, na.rm = FALSE, use) 
{
    if (missing(use)) 
        use <- if (na.rm) 
            "na.or.complete"
        else "everything"
    na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs", 
        "everything", "na.or.complete"))
    if (is.na(na.method)) 
        stop("invalid 'use' argument")
    if (is.data.frame(x)) 
        x <- as.matrix(x)
    else stopifnot(is.atomic(x))
    if (is.data.frame(y)) 
        y <- as.matrix(y)
    else stopifnot(is.atomic(y))
    .Call(C_cov, x, y, na.method, FALSE)
}
<bytecode: 0x000000000928ad30>
<environment: namespace:stats>

You can then copy that into your editor and play around with it, add your browser statement, and step through the results.

like image 60
BrodieG Avatar answered Oct 21 '22 08:10

BrodieG