Suppress error message in R

后端 未结 2 923
感情败类
感情败类 2020-12-10 11:43

I am running a simulation study in R. Occassionally, my simulation study produces an error message. As I implemented my simulation study in a function, the simulation stops

相关标签:
2条回答
  • 2020-12-10 12:21

    As suggested by the previous solution, you can use try or tryCatch functions, which will encapsulate the error (more info in Advanced R). However, they will not suppress the error reporting message to stderr by default.

    This can be achieved by setting their parameters. For try, set silent=TRUE. For tryCatch set error=function(e){}.

    Examples:

    o <- try(1 + "a")
    >  Error in 1 + "a" : non-numeric argument to binary operator
    o <- try(1 + "a", silent=TRUE)  # no error printed
    
    o <- tryCatch(1 + "a")
    > Error in 1 + "a" : non-numeric argument to binary operator
    o <- tryCatch(1 + "a", error=function(e){})
    
    0 讨论(0)
  • 2020-12-10 12:26

    There is a big difference between suppressing a message and suppressing the response to an error. If a function cannot complete its task, it will of necessity return an error (although some functions have a command-line argument to take some other action in case of error). What you need, as Zoonekynd suggested, is to use try or trycatch to "encapsulate" the error so that your main program flow can continue even when the function fails.

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