R打印警告

时间:2016-09-08 11:48:13

标签: r warnings

我在一个可以在矩阵上工作的文件上有一个代码,我使用

读取它
  

源(" filecode.r&#34)

由于代码使用的矩阵必须具有一些特定的特性,我想打印一条消息来记住用户必须使用这些特征格式化输入矩阵。

代码是这样的:

n<- nrow(aa)
d_ply(aa, 1, function(row){
cu<- dist(as.numeric(row[-1]))
cucu<- as.matrix(cu)
saveRDS(cucu, file = paste0(row$ID, ".rds"))
}, .progress='text', .print = TRUE)

理想情况下,我想在代码开始运行之前添加一条警告消息......就像这样:

Warning(“1) did you write ‘ID’ in position [1,1] of the input matrix?;  
2) is your matrix saved as a .txt? 
3) ensure that the matrix file does not have empty rows at the end”)

并收到类似&#34的问题;你想继续吗?&#34;。 提前感谢您的所有建议! 加布

1 个答案:

答案 0 :(得分:2)

将它放在文件的开头:

check <- readline(prompt="Warning!\n(1) did you write 'ID' in position [1,1] of the input matrix? \n(2) is your matrix saved as a .txt?\n(3) ensure that the matrix file does not have empty rows at the end\n\n Do you wish to continue? (y/n)")
if(check == "n") stop("Aborted.")
print(check)  #Here would follow your code instead

如果您键入&#34; y&#34;将评估以下代码。如果键入&#34; n&#34;,脚本将停止并在stop()内打印消息。

enter image description here

你也可以确保只有&#39; y&#39;和&#39; n&#39;通过将提示语句放在while循环中来接受:

check <- NA
while(!(check %in% c('y','n'))) {
  check <- readline(prompt="Warning!\n(1) did you write 'ID' in position [1,1] of the input matrix? \n(2) is your matrix saved as a .txt?\n(3) ensure that the matrix file does not have empty rows at the end\n\n Do you wish to continue? (y/n)")
}
if(check == "n") stop("Aborted.")