Reputation: 23134
Is there a function in R that behaves like this:
isnothing = function(x) {
is.null(x) | is.na(x) | is.nan(x)
}
Upvotes: 23
Views: 8224
Reputation: 3518
I believe you are basically looking for what gtools
invalid() function does.
?gtools::invalid
For example,
gtools::invalid(NA)
[1] TRUE
gtools::invalid(NULL)
[1] TRUE
gtools::invalid(NaN)
[1] TRUE
Upvotes: 10
Reputation: 5702
I had a very similar problem too. I was trying to check whether row names of a given matrix or data frame are proper.
x <- matrix(1:6,ncol=2)
isnothing = function(x) {
any(is.null(x)) | any(is.na(x)) | any(is.nan(x))
}
isnothing(rownames(x))
The function will throw an error. But when I used short circuiting and changed it to:
isnothing = function(x) {
any(is.null(x)) || any(is.na(x)) || any(is.nan(x))
}
isnothing(rownames(x))
It solved my problem. I guess checking first nullity and then going forward to check other cases if it is FALSE solved my issue. I checked it with couple problematic cases that I can think of and it worked. I don't know whether there are exceptions to it but it worked for my purposes for now.
rownames(x) <- c("a",NaN,NA)
isnothing(rownames(x))
Upvotes: 1
Reputation: 14862
I was also missing such a function and added this to my .Rprofile
ages ago. If someone knows of a base function that does the same thing I also want to know.
is.blank <- function(x, false.triggers=FALSE){
if(is.function(x)) return(FALSE) # Some of the tests below trigger
# warnings when used on functions
return(
is.null(x) || # Actually this line is unnecessary since
length(x) == 0 || # length(NULL) = 0, but I like to be clear
all(is.na(x)) ||
all(x=="") ||
(false.triggers && all(!x))
)
}
As @shadow mentioned, NA
, NaN
and NULL
have different meanings that are important to understand. However, I find this function useful when I make functions containing optional arguments with default values, that I want to allow the user to suppress by setting them to any "undefined" value.
One such example is xlab
of plot
. I can never remember if it is xlab=NA
, xlab=FALSE
, xlab=NULL
or xlab=""
. Some produce the desired result and some don't, so I found it convenient to catch all with the above function when I develop code, particularly if other people will use it too.
Upvotes: 17