Marco Breitig
Marco Breitig

Reputation: 201

R execude expression on warning/error

I process huge data sets and therefore my R program runs for several hours. Sometimes it happens that something goes wrong and the program aborts with some warning/error message. Most times this are not the warning messages I programmed myself because I thought on what could go wrong - it is something unexpected causing an warning or error in some base R function I call. For the warning messages I programmed myself I could use the expr argument of warning. Is there something similar as a global option?

R (I am using Rstudio on Win 8) is only running in the background, as I have other work to do. From time to time I tap to R to see if it is still running. In case if something goes wrong I want to raise a beep sound like beep(sound=1) from the beepr package.

Is there any way to execude some expression (like this beep(sound=1)) when a warning/error is raised? It suffices the latter as one can promote every warning to an error by options(warn=2) and it might be hard to execute some expression if R still executes some other expression which threw the warning.

Upvotes: 1

Views: 721

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

You could use tryCatch to do that in the following way:

Example that produces a warning:

x <- 1:10
y <- if (x < 5 ) 0 else 1

Warning message:
In if (x < 5) 0 else 1 :
  the condition has length > 1 and only the first element will be used

Using tryCatch

>tryCatch(if (x < 5 ) 0 else 1, 
          warning = function(x) print(x),
          finally = print('hello'))

<simpleWarning in if (x < 5) 0 else 1: the condition has length > 1 and only the first element will be used>
[1] "hello"

In the code above where I have print(hello) add beep(sound=1) and it will give you a beep sound whenever it gives a warning.

Upvotes: 3

Related Questions