How to detect null values ​​in a vector

What is the best way to detect null values ​​in a vector?

If I have a vector below and want to know that the fourth position is zero, how would I do it,

vx <- c(1, 2, 3, NULL, 5)
is.null(vx)
[1] FALSE

      

is.null () only returns 1 FAlSE and ID to get:

 FALSE FALSE FALSE TRUE FALSE

      

+3


source to share


2 answers


As stated in the comments, NULL

will not appear in length(vx)

. This is a special object in R for undefined values. From CRAN documentation:

NULL represents a null object in R: it is a reserved word. NULL - often returned by expressions and functions whose value is undefined.

But your question may still have learning opportunities regarding lists. He will appear there. How in:

vlist <- list(1, 2, 3, NULL, 5)

      



Trying to identify a value NULL

in a very large dataset can be daunting for novice R users. There are different methods, but here I work for me when I need 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 symbols, then substitute in is.character

or in relation to any class.

+5


source


Perhaps someone (like me) can find someone who is.null()

really needs is.na()

. If so, remind yourself (as I did) that R has both an object NULL

and NA

. NULL

means that there is no value, whereas NA

means that the value is unknown. If you are looking for missing values ​​in a value vector, then what you are probably after is is.na()

.



0


source







All Articles