Debugging lapply/sapply calls

后端 未结 7 738

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 08:58

    You can debug() the function, or put a browser() inside the body. This is only particularly useful if you don't have a gajillion iterations to work through.

    Also, I've not personally done this, but I suspect you could put a browser() in as part of a tryCatch(), such that when the error is generated you can use the browser() interface.

    0 讨论(0)
  • 2020-12-02 09:01

    Using debug or browser isn't a good idea in this case, because it will stop your code so frequently. Use Try or TryCatch instead, and deal with the situation when it arises.

    0 讨论(0)
  • 2020-12-02 09:02

    If you wrap your inner function with a try() statement, you get more information:

    > sapply(x, function(x) try(1/x))
    Error in 1/x : non-numeric argument to binary operator
    [1] "-0.5"                                                    
    [2] "Error in 1/x : non-numeric argument to binary operator\n"
    [3] "Inf"                                                     
    [4] "1"                                                       
    [5] "0.5"
    

    In this case, you can see which index fails.

    0 讨论(0)
  • 2020-12-02 09:05

    I've faced the same problem and have tended to make my calls with (l)(m)(s)(t)apply to be functions that I can debug().

    So, instead of blah<-sapply(x,function(x){ x+1 })

    I'd say,

     myfn<-function(x){x+1}
     blah<-sapply(x,function(x){myfn(x)})
    

    and use debug(myfn) with options(error=recover).

    I also like the advice about sticking print() lines here and there to see what is happening.

    Even better is to design a test of myfn(x) that it has to pass and to be sure it passes said test before subjecting it to sapply. I only have patience to to this about half the time.

    0 讨论(0)
  • 2020-12-02 09:09

    Use the plyr package, with .inform = TRUE:

    library(plyr)
    laply(x, function(x) 1/x, .inform = TRUE)
    
    0 讨论(0)
  • 2020-12-02 09:10

    Use the standard R debugging techniques to stop exactly when the error occurs:

    options(error = browser) 
    

    or

    options(error = recover)
    

    When done, revert to standard behaviour:

    options(error = NULL)
    
    0 讨论(0)
提交回复
热议问题