Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging a function in a different source file in R

Tags:

r

rstudio

I'm using RStudio and I want to be able to stop the code execution at a specific line.

The functions are defined in the first script file and called from a second.

I source the first file into the second one using source("C:/R/script1.R")

I used run from beginning to line: where I start running from the second script which has the function calls and have highlighted a line in the first script where the function definitions are.

I then use browser() to view the variables. However this is not ideal as there are some large matrices involved. Is there a way to make these variables appear in RStudio's workspace?

Also when I restart using run from line to end it only runs to the end of the called first script file it does not return to the calling function and complete the running of the second file.

How can I achieve these goals in RStudio?

OK here is a trivial example the function adder below is defined in one script

adder<-function(a,b) {  
  browser()
  return(a+b)
 }

I than call is from a second script

x=adder(3,4)

When adder is called in the second script is starts browser() in the first one. From here I can use get("a") to get the value of a, but the values of a and b do not appear in the workspace in RStudio?

In the example here it does not really matter but when you have several large matrices it does.

like image 468
Bazman Avatar asked Sep 20 '12 15:09

Bazman


2 Answers

If you assign the data, into the .GlobalEnv it will be shown in RStudio's "Workspace" tab.

> adder(3, 4)
Called from: adder(3, 4)
Browse[1]> a
[1] 3
Browse[1]> b
[1] 4
Browse[1]> assign('a', a, pos=.GlobalEnv)
Browse[1]> assign('b', b, pos=.GlobalEnv)
Browse[1]> c
[1] 7
> a
[1] 3
> b
[1] 4
like image 195
GSee Avatar answered Sep 30 '22 13:09

GSee


What you refer to as RStudio's workspace is the global environment in an R session. Each function lives in its own small environment, not exposing its local variables to the global environment. Therefore a is not present in the object inspector of RStudio.

This is good programming practice as it shields sections of a larger script from each other, reducing the amount of unwanted interaction. For example, if you use i as a counter in one function, this does not influence the value of a counter i in another function.

You can inspect a when you are in the browser session by using any of the usual functions. For example,

head(a)
str(a)
summary(a)
View(a)
attributes(a)

One common tactic after calling browser is to get a summary of all variables in the current (parent) environment. Make it a habit that every time you stop code with browser, you immediately type ls.str() at the command line.

like image 26
Paul Hiemstra Avatar answered Sep 30 '22 14:09

Paul Hiemstra