'behavior of browser() function in R

I am debugging a function in R using browser() and have encountered something that I don't understand. Below is a simple example function:

testf<-function(x)
{
  if(x==1) x=x+1  
  return(x) 
}

If I run this it behaves as expected:

> testf(1)
[1] 2
> testf(2)
[1] 2

Now, I insert a browser() function to enter debug mode:

testf<-function(x)
{
  browser()
  if(x==1) x=x+1
  
  return(x)
}

If I now run testf(1) and use the Next command feature in debug mode to step through the function, it produces the expected output of 2. However, if I run the if statement directly (e.g. by highlighting and pushing the Run button), x does not get incremented:

Browse[1]> x
[1] 1
Browse[1]> if(x==1) x=x+1
debug at #3: x = x + 1
Browse[3]> x
[1] 1

If I instead run x=x+1 by itself then x does get incremented:

Browse[3]> x
[1] 1
Browse[3]> x=x+1
Browse[3]> x
[1] 2
Browse[3]> 

Then x does get incremented as expected.

Why? My understanding of debug mode is that you can run any command and it will get executed as if you were running the function, but this seems not to be the case with the if statement above.

What am I missing here?

r


Solution 1:[1]

I am going to provide a more detailed answer to my question, based on Waldi's answer above. The real heart of my question is this: Why does my if statement perform differently in normal and debug modes?

> x=1
> if(x==1) x=x+1
> x
[1] 2
> testf(1)
Called from: testf(1)
Browse[1]> x
[1] 1
Browse[1]> if(x==1) x=x+1
debug at #3: x = x + 1
Browse[3]> x
[1] 1

The answer can be seen by using the debugger to step through the function. When I use the Next tool to step through the if, it takes two steps to get through rather than the one step that we might expect. This is because the if involves two steps:

  1. Evaluate condition
  2. Execute command.

Normally, these are executed together at one time. However, the debugger separates them. This is presumably because it is possible that an error could be in either the evaluation step or the execution step. This is sensible, but it has the side effect that if I run the if at the command line in debug mode, it only executes the first part (evaluate) and not the second part (execute).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul S