如何在R中测试当条件返回numeric(0)时

40

假设你想基于条件setdiff(input, 1:9)构建一个简单的测试。

我该如何构建一个

if isnotempty(setdiff(input, 1:9)) stop ("not valid") 

当输入为c(3, 12)时停止执行,但当输入为c(2,5,7)时继续执行的语句是什么?

1
在这里检查“input”是否为数字也是不错的选择。+1 给 @TylerRinker 处理它 :) - daroczig
6个回答

56

你可以使用?length

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

input <- c(3, 12);

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

1
谢谢,我需要这个来完成我的彩票生成器 ;) Bertie. - Bertie

26
这里还有另一个选项 identical(x, numeric(0))。这是一个例子(基本上是从sgibb那里拿过来的,只是替换了关键行,因为我懒)。
isEmptyNumeric <- function(x) {
    return(identical(x, numeric(0)))
}

input <- c(3, 12)

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

1
我喜欢这种更加明确(易读)和具体的方式。例如,如果 x = character(0),则 length(x) == 0 返回 TRUE,而 identical(x, numeric(0)) 返回 FALSE。 - Jonas Lindeløv

4

我使用了以下函数:

# 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)
}

希望它能有所帮助。

0

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

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

0

这并不回答你主题行中的问题,但我认为这是实现你想要达到的目标的更好方法:

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

0
另一个选择是rlang::is_bare_numeric()函数

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接