R - Rstudio - 如果生成警告/错误,则让R播放声音

时间:2015-08-19 19:58:08

标签: r rstudio

我正在运行一个循环遍历股票对组合列表的脚本......由于对组合之间的不同数据长度产生的错误,我偶尔会停止运行脚本,我只是从考虑中删除不匹配的股票):

Error in model.frame.default(formula = stckY ~ stckX + 0, drop.unused.levels = TRUE) : 
  variable lengths differ (found for 'stckX')

当出现错误信息时,有什么方法可以让R / Rstudio发出声音,这样我就可以在脚本循环时不必盯着屏幕就能收到警报吗?

我可以使用以下方式线性生成声音:

beep <- function(n = 3){
    for(i in seq(n)){
        system("rundll32 user32.dll,MessageBeep -1")
        Sys.sleep(.5)
    }
}
beep()

但我怎么能以错误信息为条件来做这件事呢?

2 个答案:

答案 0 :(得分:0)

尝试选项(错误=哔哔声)

在执行此操作之前,您仍需要定义蜂鸣声。尚未验证此作品,但它应该是每个选项:

'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'.

答案 1 :(得分:0)

以@frankc答案和@hrbrmstr注释为基础,这是一种实现方法:

install.packages("beepr")
library(beepr)
options(error = beep)