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等)
- R: 循环语句中warning()的显示问题
- R语言中条件及循环语句的应用
- R语言-循环语句
- R循环语句
- 关于在DELPHI中FOR循环语句的使用问题
- C中printf循环输出不及时显示的问题
- 织梦循环中图片不显示的问题
- 关于for的循环语句的问题
- 关于循环语句的一些问题
- C++/ C循环语句的效率问题
- JavaScript循环语句的性能问题[旧]
- JavaScript循环语句的性能问题
- R中关于显示标签的几个问题
- 关于goto语句能不能从复杂的嵌套循环判断中跳出去的问题讨论
- 关于goto语句能不能从复杂的嵌套循环判断中跳出去的问题讨论
- 关于goto语句能不能从复杂的嵌套循环判断中跳出去的问题讨论
- 关于goto语句能不能从复杂的嵌套循环判断中跳出去的问题讨论
- 关于goto语句能不能从复杂的嵌套循环判断中跳出去的问题讨论
- 富豪们掌握着获得智慧的智慧
- poj 1308 Is It A Tree?
- 导入源码步骤
- 1153. Word Reversal
- 如何删除访问局域网共享时所保存的用户名及密码
- R: 循环语句中warning()的显示问题
- 昆虫繁殖
- 算法之旅——二分查找
- 【LeetCode】Merge k Sorted Lists
- 儿童业态放公司梵蒂冈仿盛大
- Cocos2d-x中移植到Android真机上屏幕方向设置
- css代码是放在html代码的哪个位置
- vim简明教程
- 解决FTP上传时报未能解析远程名称或未能解析域名错误方