假设你想基于条件setdiff(input, 1:9)
构建一个简单的测试。
我该如何构建一个
if isnotempty(setdiff(input, 1:9)) stop ("not valid")
当输入为
c(3, 12)
时停止执行,但当输入为c(2,5,7)
时继续执行的语句是什么?假设你想基于条件setdiff(input, 1:9)
构建一个简单的测试。
我该如何构建一个
if isnotempty(setdiff(input, 1:9)) stop ("not valid")
c(3, 12)
时停止执行,但当输入为c(2,5,7)
时继续执行的语句是什么?你可以使用?length
:
isEmpty <- function(x) {
return(length(x)==0)
}
input <- c(3, 12);
if (!isEmpty(setdiff(input, 1:9))) {
stop ("not valid")
}
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")
}
x = character(0)
,则 length(x) == 0
返回 TRUE,而 identical(x, numeric(0))
返回 FALSE。 - Jonas Lindeløv我使用了以下函数:
# 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)
}
我喜欢isEmpty函数。我提议以下方式,以防您解析向量或列表:
isEmpty <- function(x) {
s<-sapply(x, function(y) length(y)==0, simplify = T)
return(s)
}
这并不回答你主题行中的问题,但我认为这是实现你想要达到的目标的更好方法:
if(!all(input %in% 1:9)) stop("not valid")
rlang::is_bare_numeric()
函数