How to force an error if non-finite values (NA, NaN, or Inf) are encountered

后端 未结 2 747
南笙
南笙 2021-01-02 03:27

There\'s a conditional debugging flag I miss from Matlab: dbstop if infnan described here. If set, this condition will stop code execution when an Inf

2条回答
  •  天涯浪人
    2021-01-02 04:06

    The idea sketched below (and its implementation) is very imperfect. I'm hesitant to even suggest it, but: (a) I think it's kind of interesting, even in all of its ugliness; and (b) I can think of situations where it would be useful. Given that it sounds like you are right now manually inserting a check after each computation, I'm hopeful that your situation is one of those.

    Mine is a two-step hack. First, I define a function nanDetector() which is designed to detect NaNs in several of the object types that might be returned by your calculations. Then, it using addTaskCallback() to call the function nanDetector() on .Last.value after each top-level task/calculation is completed. When it finds an NaN in one of those returned values, it throws an error, which you can use to avoid any further computations.

    Among its shortcomings:

    • If you do something like setting stop(error = recover), it's hard to tell where the error was triggered, since the error is always thrown from inside of stopOnNaNs().

    • When it throws an error, stopOnNaNs() is terminated before it can return TRUE. As a consequence, it is removed from the task list, and you'll need to reset with addTaskCallback(stopOnNaNs) it you want to use it again. (See the 'Arguments' section of ?addTaskCallback for more details).

    Without further ado, here it is:


    # Sketch of a function that tests for NaNs in several types of objects
    nanDetector <- function(X) {
       # To examine data frames
       if(is.data.frame(X)) { 
           return(any(unlist(sapply(X, is.nan))))
       }
       # To examine vectors, matrices, or arrays
       if(is.numeric(X)) {
           return(any(is.nan(X)))
       }
       # To examine lists, including nested lists
       if(is.list(X)) {
           return(any(rapply(X, is.nan)))
       }
       return(FALSE)
    }
    
    # Set up the taskCallback
    stopOnNaNs <- function(...) {
        if(nanDetector(.Last.value)) {stop("NaNs detected!\n")}
        return(TRUE)
    }
    addTaskCallback(stopOnNaNs)
    
    
    # Try it out
    j <- 1:00
    y <- rnorm(99)
    l <- list(a=1:4, b=list(j=1:4, k=NaN))
    # Error in function (...)  : NaNs detected!
    
    # Subsequent time consuming code that could be avoided if the
    # error thrown above is used to stop its evaluation.
    

提交回复
热议问题