Reputation: 1193
Let's imagine you would like to construct a simple test based on the condition setdiff(input, 1:9)
.
How can I construct an
if isnotempty(setdiff(input, 1:9)) stop ("not valid")
statement which stops execution when input is c(3, 12)
but continues when input is c(2,5,7)
say?
Many thanks,
Bertie
Upvotes: 40
Views: 75303
Reputation: 109874
Here's another option identical(x, numeric(0))
. Here's an example (basically took everything from sgibb and replaced the key line as I'm lazy):
isEmptyNumeric <- function(x) {
return(identical(x, numeric(0)))
}
input <- c(3, 12)
if (!isEmptyNumeric(setdiff(input, 1:9))) {
stop ("not valid")
}
Upvotes: 26
Reputation: 3043
I used the following functions:
# 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)
}
Hope it will be useful.
Upvotes: 3
Reputation: 103
I liked the isEmpty function. I propose the following, just in case you parse a vector, or a list:
isEmpty <- function(x) {
s<-sapply(x, function(y) length(y)==0, simplify = T)
return(s)
}
Upvotes: 0
Reputation: 89067
This does not answer the question in your subject line, but I think it is a better approach for what you are trying to achieve:
if(!all(input %in% 1:9)) stop("not valid")
Upvotes: 0
Reputation: 25736
You could use ?length
:
isEmpty <- function(x) {
return(length(x)==0)
}
input <- c(3, 12);
if (!isEmpty(setdiff(input, 1:9))) {
stop ("not valid")
}
Upvotes: 57