r - 在 if else 语句中未强制执行 R stop() 函数
问题描述
我正在尝试使用以下内容自动对我的 R 脚本的某些部分进行质量检查:
... other R code before...
if( Table1$date==Sys.Date() ){print("Successful check, all good to proceed")
}else{print("Execution stopped. Check Table1");stop()}
... other R code after...
在检查失败的情况下,我确实看到了以下消息,但是 R 脚本继续运行而不会停止,因为它预期会从stop()
命令中运行。我该如何解决这个问题?
[1] "Execution stopped. Check Table1"
Error:
解决方案
我假设您在交互式 R 会话中运行它,可能是 RStudio。在这种情况下,当您运行整个文件时,每一行的执行都独立于前一行的成功或失败。stop()
如果您从操作系统命令行/终端运行脚本,当if()
语句的条件为 FALSE时,它将在 , 处中断。
试试这个,看看条件为 FALSE 时会发生什么:
Rscript -e 'if(FALSE){print("Successful check, all good to proceed"}
else{print("Execution stopped. Check Table1");stop()};a<-1;a'
试试这个,看看条件为真时会发生什么:
Rscript -e 'if(TRUE){print("Successful check, all good to proceed"}
else{print("Execution stopped. Check Table1");stop()};a<-1;a'
要实现您正在寻找的行为,您可以使用或 [edit:] 从操作系统命令行/终端执行整个文件,Rscript
只需将进一步的代码移动到 if 语句中
像这样的东西应该工作:
if (check_date == Sys.Date()) {
print("Successful check, all good to proceed")
# more code here
} else {
stop("Execution stopped. Check Table1")
}
}