问题
I am running a script that loops over a list of stock pair combinations... occasionally the script stops running due to an error generated by differing data lengths between pair combo and I simply remove the mismatched stock from consideration):
Error in model.frame.default(formula = stckY ~ stckX + 0, drop.unused.levels = TRUE) :
variable lengths differ (found for 'stckX')
Is there any way I can make R / Rstudio play a sound when the error message occurs so that I can be alerted without having to keep my eyes on the screen while the script is looping along?
I can generate sounds linearly using:
beep <- function(n = 3){
for(i in seq(n)){
system("rundll32 user32.dll,MessageBeep -1")
Sys.sleep(.5)
}
}
beep()
but how can I do this conditional on an error message?
回答1:
Building on @frankc answer and @hrbrmstr comment, a way to do this:
install.packages("beepr")
library(beepr)
options(error = beep)
回答2:
try options(error = beep)
you would still need to define beep before you do this. Haven't verified this works but it should per ?options:
'error': either a function or an expression governing the handling of non-catastrophic errors such as those generated by 'stop' as well as by signals and internally detected errors. If the option is a function, a call to that function, with no arguments, is generated as the expression. The default value is 'NULL': see 'stop' for the behaviour in that case. The functions 'dump.frames' and 'recover' provide alternatives that allow post-mortem debugging. Note that these need to specified as e.g. 'options(error = utils::recover)' in startup files such as '.Rprofile'.
来源:https://stackoverflow.com/questions/32104555/r-rstudio-make-r-play-a-sound-if-warning-error-generated