如何在条件中返回R中的数字(0)时进行测试

Ber*_*tie 30 r

让我们假设你想根据条件构建一个简单的测试setdiff(input, 1:9).

我怎样才能构建一个

if isnotempty(setdiff(input, 1:9)) stop ("not valid") 
Run Code Online (Sandbox Code Playgroud)

在输入时停止执行c(3, 12)但在输入时继续执行的语句c(2,5,7)?非常感谢,伯蒂

sgi*_*ibb 41

你可以使用?length:

isEmpty <- function(x) {
    return(length(x)==0)
}

input <- c(3, 12);

if (!isEmpty(setdiff(input, 1:9))) {
    stop ("not valid")
}
Run Code Online (Sandbox Code Playgroud)


Tyl*_*ker 14

这是另一种选择identical(x, numeric(0)).这是一个例子(基本上从sgibb中获取所有内容并替换了关键行,因为我很懒惰):

isEmpty <- function(x) {
    return(identical(x, numeric(0)))
}

input <- c(3, 12)

if (!isEmpty(setdiff(input, 1:9))) {
    stop ("not valid")
}
Run Code Online (Sandbox Code Playgroud)