Kinformationist
Kinformationist

Reputation: 324

tryCatch in R execute in case of error

Is it possible to execute certain commands in case of error when using tryCatch in R ? I am using the code below but it does not execute X = alternative_value

tryCatch(
{
  X = certain_function_that_sometimes_returns_error      
},
error=function(e) {
  X = alternative_value
})

Upvotes: 8

Views: 26716

Answers (1)

SymbolixAU
SymbolixAU

Reputation: 26258

Assign your tryCatch directly to x

foo <- function() stop("hello")  ## initiate an error using `stop()`
bar <- function() 'world'
    
x <- tryCatch( 
  {
    foo()
  },
  error = function(e) {
    bar()
  }
)
    
x
# [1] "world"

Upvotes: 29

Related Questions