Debugging lapply/sapply calls

后端 未结 7 739

Code written using lapply and friends is usually easier on the eyes and more Rish than loops. I love lapply just as much as the next guy, but how do I debug it when things

相关标签:
7条回答
  • 2020-12-02 09:17

    Like geoffjentry said:

    > sapply(x, function(x) {
      res <- tryCatch(1 / x,
                      error=function(e) {
                              cat("Failed on x = ", x, "\n", sep="") ## browser()
                              stop(e)
                            })
    })
    

    Also, your for loop could be rewritten to be much cleaner (possibly a little slower):

    > y <- NULL
    > for (xi in x)
        y <- c(y, 1 / xi)
    
    Error in 1/xi : non-numeric argument to binary operator
    

    For loops are slow in R, but unless you really need the speed I'd go with a simple iterative approach over a confusing list comprehension.

    If I need to figure out some code on the fly, I'll always go:

    sapply(x, function(x) {
      browser()
      ...
    })
    

    And write the code from inside the function so I see what I'm getting.

    -- Dan

    0 讨论(0)
提交回复
热议问题