I'm encountering an unusual behavior when using the debug function in RStudio. I've defined a function and used debugSource to source the script, but the debugging experience is not as expected.
Here's what I've done:
Defined the function:
test <- function(x) {
browser()
y <- x^2
return(y)
}
Sourced the script:debugSource("~/1.R")
Called the function: test(1)
Expected behavior:
I expected to enter a graphical debugging mode within the RStudio IDE.
I should be able to use buttons like "Step" and "Continue" to control the debugging process.
The "Environment" pane should display the values of variables in the current environment.
I've attached an image showing the expected behavior, which I've observed on a different server:
To debug within RStudio, you do not need to insert the browser() function (although it is harmless to do so, I think). Source the script, put the cursor in line 2 and use the Toggle Breakpoint command to set a breakpoint. (You can also set the breakpoint first and then source the script.) Now execute test(1) in the console. You'll get the behavior seen in the first screenshot.
Did you save the script to a file? Here is what I see after (1) creating and saving the script, (2) setting the breakpoint and (3) invoking the function in the console.
Your example works perfectly fine. When I SOURCE a script with a breakpoint set, the break point is reached but the green arrow does not appear in the code editor
This apparently has something to do with where the breakpoints are and whether you are executing the function or sourcing the script.
When I try your script by executing test(3) in the console, I get the arrow. When I source the script, I do not. When I call debugSource() (an RStudio function with a curious lack of documentation), I do not get the arrow.
Try the following, using your script. Move the breakpoint to the print command (taking it off line 2) and source the script. What happens for me is that the debugger is entered with no green arrow in the code window. Now click the debugger button to step into the function (or use the command "s"). I get a new code tab with the following content.
function (x, ...)
UseMethod("print")
I also get a green arrow pointing to the second line. Step in another level and focus returns to the original code tab with a green arrow in line 1. Click "Next" or execute "n" and the arrow moves to line 2, and so on.
I have no idea why sourcing (or using debugSource) does not have an arrow pointing to where the code is paused. In any case, stepping into the code will bring up the arrow.
Paul,
I believe there is a new bug introduced into R Studio. This behavior was not present in older versions of RStudio. I always got the green arrow when using breakpoints when I sourced or called the program from debugSource().. Furthermore, STEP INTO only produces the green arrow when stepping into a function, not to the next executable line. How can we get this fixed?