Make R beep when R Markdown finishes – or when it fails.

I often run time-consuming scripts, so I’m a big fan of ‘s Rasmus Bååth beepr package in R. I often put beep() at the end of my .R files to let me know when analyses are done.

However, when using R Markdown and knitr in RStudio, this is a poor solution when there is an error somewhere in my script. This is because knitr will terminate its R session before it gets to my beep() line at the end.

One way to get around this is to assign what R does on an error and what it does when it runs an .Rmd script successfully. Once the beepr package is installed, running the following markdown chunk at the beginning of the file will make .Rmd beep when it exits normally, or due to error:

```{r echo = F}
options(error = function(){    # Beep on error
  beepr::beep()
  Sys.sleep(1)
  }
 )

.Last <- function() {          # Beep on exiting session
  beepr::beep()
  Sys.sleep(1)
  }
```

The reason Sys.sleep(1) is there to give knitr some time to actually play the sounds before terminating.

NB. If you accidentally set this in your workspace outside knitr (i.e. running chunks in the console), getting a beep on every error can be super annoying. In that case, reset it with the following code:

options(error = NULL)

Hope someone finds this useful!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s