Debugging a function in another source file in R

I am using RStudio and I want to stop the execution of code on a specific line.

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

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

I used the run from start to line: where I run the second script that has function calls, and highlighted the line in the first script where the function definitions are located.

Then I use browser() to view the variables. However, this is not ideal, as there are some large matrices. Is there a way to turn these variables into an RStudio workspace?

In addition, when I restart the use of run from line to end, it runs only until the end of the first script file called, it does not return to the calling function and does not shut down the second file.

How can I achieve these goals in RStudio?

Ok, here is a trivial example: the function adder is defined below in one script

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

I than the call from the second script

 x=adder(3,4) 

When the adder is called in the second script, it launches the browser () in the first. 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 this example, this does not really matter, but when you have several large matrices, it does.

+4
source share
2 answers

If you assign data, in .GlobalEnv it will appear on the RStudio 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 
+2
source

What you call the RStudio workspace is the global environment in the R session. Each function lives in its own small environment, without exposing its local variables to the global environment. Therefore, a not in the RStudio object inspector.

This is a good programming practice because it protects 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 affect the value of counter i in another function.

You can check a while in a browser session using any of the usual functions. For instance,

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

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

+3
source

Source: https://habr.com/ru/post/1435321/


All Articles