R Script - How to Continue Code Execution on Error

后端 未结 3 1955
挽巷
挽巷 2020-11-30 08:37

I have written an R script which includes a loop that retrieves external (web) data. The format of the data are most of the time the same, however sometimes the format chang

相关标签:
3条回答
  • 2020-11-30 09:10

    You can use try:

    # a has not been defined
    for(i in 1:3)
    {
      if(i==2) try(print(a),silent=TRUE)
      else print(i)
    }
    
    0 讨论(0)
  • 2020-11-30 09:10

    How about these solutions on this related question :

    Is there a way to `source()` and continue after an error?

    Either parse(file = "script.R") followed by a loop'd try(eval()) on each expression in the result.

    Or the evaluate package.

    0 讨论(0)
  • 2020-11-30 09:16

    Use try or tryCatch.

    for(i in something)
    {
      res <- try(expression_to_get_data)
      if(inherits(res, "try-error"))
      {
        #error handling code, maybe just skip this iteration using
        next
      }
      #rest of iteration for case of no error
    }
    

    The modern way to do this uses purrr::possibly.

    First, write a function that gets your data, get_data().

    Then modify the function to return a default value in the case of an error.

    get_data2 <- possibly(get_data, otherwise = NA)
    

    Now call the modified function in the loop.

    for(i in something) {
      res <- get_data2(i)
    }
    
    0 讨论(0)
提交回复
热议问题