R - Rstudio - make R play a sound if warning/error generated

一世执手 提交于 2020-12-12 12:32:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!