如果我的函数(x,y,z)在R 中输入,我想写一行代码,确保数据x的形式正确.
ie x只是一个实数而不是其他任何东西,如矢量或列表.我假设代码会像
if ( ... ){stop("x must be a real number")}
Run Code Online (Sandbox Code Playgroud)
我想知道括号里面的内容而不是...?
原因是如果我在向量中写入,程序只需将向量的第一个分量作为输入.R会对此发出警告,但我希望该程序能够立即停止.
如果您想要"停止",如果您的参数长度为1,并且是实数
你可以用 stopifnot
foo <- function(x, y, z) {
stopifnot(length(x)==1L & is.numeric(x))
}
Run Code Online (Sandbox Code Playgroud)
也许
foo <- function(x, y, z){
if(!(length(x)==1L & is.numeric(x))) { stop("x must be a real number")}
}
Run Code Online (Sandbox Code Playgroud)
stop允许您指定错误消息,而stopifnot将返回已测试的条件.(两者都有优势)
好处stopifnot是它可以准确地告诉你多个条件中的哪一个失败.例如(注意我现在正在提供多个表达式)
foo <- function(x, y, z) {
stopifnot(length(x)==1L , is.numeric(x))
}
foo('a')
# Error: is.numeric(x) is not TRUE
foo(c(1,2))
# Error: length(x) == 1L is not TRUE
Run Code Online (Sandbox Code Playgroud)