Home > OS >  When debugging in RStudio, how to operate an object in another function in the stack?
When debugging in RStudio, how to operate an object in another function in the stack?

Time:10-11

I have a basic question with RStudio as following.

When I run the following R code in RStudio, it will pause at browser() in function f3(). At that point, I want to operate on the object i1 in function f1(). For example, I want to print(i1).

However, I found that I cannot do it. Does anyone know how to do it?

f1 <- function() {
    i1 <- 1
    f2()
}

f2 <- function() {
    i2 <- 2
    f3()
}

f3 <- function() {
    i3 <- 3
    browser()
}

f1()

enter image description here

CodePudding user response:

Each level of function call comes with its own environment. You can access them with the parent.frame function.

Browse[1]> ls()
[1] "i3"
Browse[1]> ls(parent.frame())
[1] "i2"
Browse[1]> ls(parent.frame(2))
[1] "i1"
Browse[1]> ls(parent.frame(3))
[1] "f1" "f2" "f3"

The last one above is the global environment.

Then you can get or change a value:

Browse[1]> get("i1", envir = parent.frame(2))
[1] 1
Browse[1]> assign("i1", 10, envir = parent.frame(2))
Browse[1]> get("i1", envir = parent.frame(2))
[1] 10

Here is a function to get the value of a local variable in any parent frame:

getval <- function(name) {
  i <- 0
  repeat {
    i <- i   1
    e <- parent.frame(i)
    if (exists(name, envir = e)) return(get(name, envir = e))
    if (identical(e, .GlobalEnv)) break
  }
}

Browse[1]> getval("i3")
[1] 3
Browse[1]> getval("i2")
[1] 2
Browse[1]> getval("i1")
[1] 10

You may write an equivalent setval function if necessary.

CodePudding user response:

If you only want to look at the values of other functions that have been called in the process of the script you can use the traceback functionality shown here on the bottom right:

enter image description here

If you select f1() there, you will see the value of i1 directly in the Environment view:

enter image description here

  • Related