Getting the state of variables after an error occurs in R

后端 未结 3 757
谎友^
谎友^ 2020-12-02 21:21

Let\'s say I have just called a function, f, and an error occurred somewhere in the function. I just want to be able to check out the values of different varia

相关标签:
3条回答
  • 2020-12-02 21:43

    options(error=recover)

    Probably answers the question best. However, I wanted to mention another handy debugging tool, traceback(). Calling this right after an error has occurred is often enough to pinpoint the bug.

    0 讨论(0)
  • 2020-12-02 21:53

    As pointed out here, there's an easy way to do this, and I think this trick has the potential to change lives for the better.

    First, call this:

    options(error=recover)
    

    Now when we call f(x,y) we will have an option to choose an environment to recover. Here I select option 1, which opens up a debugger and lets me play around with variables just before lm() is called.

    > f(x,y)
    Error in model.frame.default(formula = y ~ x, drop.unused.levels = TRUE) : 
      variable lengths differ (found for 'x')
    
    Enter a frame number, or 0 to exit   
    
    1: f(x, y)
    2: lm(y ~ x)
    3: eval(mf, parent.frame())
    4: eval(expr, envir, enclos)
    5: model.frame(formula = y ~ x, drop.unused.levels = TRUE)
    6: model.frame.default(formula = y ~ x, drop.unused.levels = TRUE)
    
    Selection: 1
    Called from: eval(expr, envir, enclos)
    Browse[1]> x
    [1] 1 2 3 4 5
    Browse[1]> y
    [1] 1.6591197 0.5939368 4.3371049 4.4754027 5.9862130 1.0000000
    
    0 讨论(0)
  • 2020-12-02 22:07

    You could also just use the debug() function:

    > debug(f)
    > f(x,y)
    debugging in: f(x, y)
    debug: {
        y <- c(y, 1)
        lm(y ~ x)
    }
    Browse[1]> 
    debug: y <- c(y, 1)
    Browse[1]> x
    [1] 1 2 3 4 5
    Browse[1]> y
    [1] 2.146553 2.610003 2.869081 2.758753 4.433881
    
    0 讨论(0)
提交回复
热议问题