Tlatwork
Tlatwork

Reputation: 1525

How to run for loop in debug mode within RStudio?

I have the following Code to get a reproducible error:

cc <- function(){
  a(2)  
}

a <- function(b){

  x <- rep(NA, 3)
  for(nr in 1:3){
    x[nr] <- nr
  }
  a*2

}

cc()

(Note that this is a sample error, i am not interested to solve. It is just a minimal reproducible example that allows me to have an example where we get in debug mode).

I use RStudio with the Debugging Settings: "Break in Code" (Debug - On Error - Break in Code).

While Debugging i want to run the for loop but i can`t:

> cc()
Error in a * 2 : non-numeric argument to binary operator
Called from: a(2)
Browse[1]> x <- NULL
Browse[1]> for(nr in 1:3){
+     x[nr] <- nr
+   }
debug at #2: x[nr] <- nr
Browse[4]> x
NULL

Question:

How can i run for-loops, if Statements, while, etc. in debug mode (and store the corresponding results in the "debugging Environment")?

(To be precise i can run the Code, as one can see in the example above. But the value of x does not Change).

Edit: Why would i want this?

Sometimes i hit an unexpected error in my Code and to better understand it i wish to execute the Code before / after that specific "error part" of my code. This works great, except that the results of running the for loop are not saved to the "temporary debug Environment" as shown in the example.

So replacing the for loop with sapply or similar would not solve it as the same challenge holds for while, if, etc.

What i tried:

I would expect that the Content within a loop is not an additional Environment i would be able to Access via recover(),...

Attempt to follow James Curran´s solution:

> debug(cc)
> cc()
debugging in: cc()
debug at
 #1: {
    a(2)
}
Browse[2]> debug(a)
Browse[2]> a(2)
debugging in: a(2)
debug at #1: {
    x <- rep(NA, 3)
    for (nr in 1:3) {
        x[nr] <- nr
    }
    a * 2
}
Browse[4]> x <- rep(NA, 3)
Browse[4]> for(nr in 1:3){
+     x[nr] <- nr
+   }
debug at #2: x[nr] <- nr
Browse[5]> a*2
Error in a * 2 : non-numeric argument to binary operator
Browse[7]> x
[1] NA NA NA

I dont seem to have changed X, (I hope i followed the instructions correctly).

Upvotes: 9

Views: 3743

Answers (2)

Super Mario
Super Mario

Reputation: 939

What about this try?

> debug(a)
> cc()

In this way, the debug starts to work only in a function. ps

Upvotes: 4

James Curran
James Curran

Reputation: 1304

Use the debug function in R. Before you call cc execute

debug(cc)

Then call cc. Once you enter cc in debug mode, you probably want to debug a as well, so type

debug(a)

And proceed.

Upvotes: 0

Related Questions