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!
Thank you for this code