How to detect null values in a vector

青春壹個敷衍的年華 提交于 2020-06-27 07:10:11

问题


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

回答1:


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.




回答2:


Its possible that someone (like me) may come looking for is.null(), really needing is.na(). If so, remind yourself (as I did) that R has both a NULL and NA object. NULL signifies that there is no value whereas NA signifies that the value is unknown. If you are looking for missing values in a vector of values, what you're probably after is is.na().



来源:https://stackoverflow.com/questions/30716377/how-to-detect-null-values-in-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!