Whats the best way to detect null values in a vector?
If I have the vector below and want to know that the 4th position is null how would I do that?
vx <- c(1, 2, 3, NULL, 5)
is.null()
returns only FALSE
:
is.null(vx)
# [1] FALSE
and I'd like to get:
FALSE FALSE FALSE TRUE FALSE
A vector can't contain NULL .
You can use the is. null function in R to test whether a data object is NULL.
The R function is. null indicates whether a data object is of the data type NULL (i.e. a missing value). The function returns TRUE in case of a NULL object and FALSE in case that the data object is not NULL.
As mentioned in the comments, NULL
will not appear in length(vx)
. It is a special object in R for undefined values. From CRAN documentation:
NULL represents the null object in R: it is a reserved word. NULL is often returned by expressions and functions whose value is undefined.
But your question can still have learning opportunities with respect to lists. It will show up there. As in:
vlist <- list(1, 2, 3, NULL, 5)
Trying to identify the NULL
value in a very large dataset can be tricky for novice R users. There are different techniques, but here is one that worked for me when I needed it.
!unlist(lapply(vlist, is.numeric))
[1] FALSE FALSE FALSE TRUE FALSE
#or as user Kara Woo added. Much better than my convoluted code
sapply(vlist, is.null)
[1] FALSE FALSE FALSE TRUE FALSE
#suggestion by @Roland
vapply(vlist, is.null, TRUE)
[1] FALSE FALSE FALSE TRUE FALSE
If there are characters, then substitute in is.character
or whatever class applies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With