How to write trycatch in R

前端 未结 5 2310
灰色年华
灰色年华 2020-11-21 23:03

I want to write trycatch code to deal with error in downloading from the web.

url <- c(
    \"http://stat.ethz.ch/R-manual/R-devel/library/ba         


        
5条回答
  •  佛祖请我去吃肉
    2020-11-21 23:27

    Here goes a straightforward example:

    # Do something, or tell me why it failed
    my_update_function <- function(x){
        tryCatch(
            # This is what I want to do...
            {
            y = x * 2
            return(y)
            },
            # ... but if an error occurs, tell me what happened: 
            error=function(error_message) {
                message("This is my custom message.")
                message("And below is the error message from R:")
                message(error_message)
                return(NA)
            }
        )
    }
    

    If you also want to capture a "warning", just add warning= similar to the error= part.

提交回复
热议问题