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

如何测试条件在R中何时返回数字(0),r,R,假设您希望基于条件setdiff(输入,1:9)构建一个简单的测试 我如何构建一个 if isnotempty(setdiff(input, 1:9)) stop ("not valid") 语句,当输入为c(3,12)时停止执行,但当输入为c(2,5,7)时继续执行? 非常感谢,, 伯蒂你可以使用?长度: isEmpty <- function(x) { return(length(x)==0) } input <- c(3, 12); if (!isEmpty(s

假设您希望基于条件
setdiff(输入,1:9)
构建一个简单的测试

我如何构建一个

if isnotempty(setdiff(input, 1:9)) stop ("not valid") 
语句,当输入为
c(3,12)
时停止执行,但当输入为
c(2,5,7)
时继续执行? 非常感谢,,
伯蒂

你可以使用
?长度

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

input <- c(3, 12);

if (!isEmpty(setdiff(input, 1:9))) {
    stop ("not valid")
}

isEmpty这里有另一个选项
相同(x,数字(0))
。下面是一个示例(基本上是从sgibb中提取所有内容,并替换关键行,因为我很懒):


isEmpty这并不能回答您的主题行中的问题,但我认为这是一个更好的方法来实现您的目标:

 if(!all(input %in% 1:9)) stop("not valid")

我喜欢isEmpty函数。我提出以下建议,以防您解析向量或列表:

isEmpty <- function(x) {
s<-sapply(x, function(y) length(y)==0, simplify = T)
return(s)
}

isEmpty我使用了以下函数:

# 1. Check if 'integer(0)'
is.integer0 <- function(x) {
  is.integer(x) && length(x) == 0L
}

# 2. Check if 'numeric(0)'
is.numeric0 <- function(x) {
  identical(x, numeric(0))
}

# 3. Check is 'integer0' or 'numeric0'
is.int_num_0 <- function(x) {
  is.integer0(x) || is.numeric0(x)
}
#1。检查是否为“整数(0)”

is.integer0检查
输入是否为数字也很好+感谢@Tylerlinker处理了这个问题:)谢谢,我需要这个来完成我的彩票生成器;)伯蒂,我喜欢这样更明确(易读)和具体。例如,如果
x=字符(0)
长度(x)==0
返回TRUE,而
相同(x,数字(0))
返回FALSE。
# 1. Check if 'integer(0)'
is.integer0 <- function(x) {
  is.integer(x) && length(x) == 0L
}

# 2. Check if 'numeric(0)'
is.numeric0 <- function(x) {
  identical(x, numeric(0))
}

# 3. Check is 'integer0' or 'numeric0'
is.int_num_0 <- function(x) {
  is.integer0(x) || is.numeric0(x)
}