R: 循环语句中warning()的显示问题

来源:互联网 发布:矩阵分解优化问题 编辑:程序博客网 时间:2024/04/30 18:20

一下是我一个R的自定义函数的一段内容,期望得到的效果是通过readline()得到用户输入的变量名,如果此变量名存在于现有的database里,则跳出这个loop,如果不在其中,则会跳出一段warning message,并重复提示"Please specify the variable name:" (readline()和warning()同时循环)。

  repeat{    resp <- as.character(readline("Please specify the variable name: "))    check1 <- resp %in% names(df)    if (check1 == TRUE){      break    }else{      warning(paste("The variable '", resp, "' does not exist in the database!", sep=""))    }      }

但是效果并不像预期一样有效:如果输入的变量名有误,那么循环会直接跳到readline()那一段而不会显示warning message。直到输入正确变量名,或者按Esc键退出自定义函数以后以前所有循环中产生的warning的信息才会一起弹出。

如何解决呢?

R有一个神奇的函数,叫options(),其中有一个参数warn是针对warning()的设置的。

关于这个参数,R的help中是这样描述的:


warn:

sets the handling of warning messages. If warn is negative all warnings are ignored. If warn is zero (the default) warnings are stored until the top–level function returns. If 10 or fewer warnings were signalled they will be printed otherwise a message saying how many were signalled. An object called last.warning is created and can be printed through the function warnings. If warn is one, warnings are printed as they occur. If warn is two or larger all warnings are turned into errors.


翻译过来是这样(只列主要几个参数):

  • warn如果是负数,则所有warning message都被忽略
  • warn = 0 (0为默认值),则所有warning messages会被储存起来直到上级函数(此例中则是repeat()函数)运行结束
  • warn = 1,则一旦产生warning message,这条信息会被立即显示出来
  • warn = 2 或更大的数值, 则warning message会被立即显示并转换成error message。此例中,如果warn = 2,整个自定义函数都会被中断,提示warning message的内容,但是会以error message的形式弹出。

所以此例中,我们需要添加一段warn = 1的option。这样就可以得到我们想要的结果了。

  repeat{    option(warn =1)    resp <- as.character(readline("Please specify the variable name: "))    check1 <- resp %in% names(df)    if (check1 == TRUE){      break    }else{      warning(paste("The variable '", resp, "' does not exist in the database!", sep=""))    }      }

此例中用到的循环函数式repeat(),但是option(warn = *)也适用于其他loop语句中(如for, while等)

0 0
原创粉丝点击