如何检测向量中的空值

How to detect null values in a vector

检测向量中空值的最佳方法是什么?

如果我有下面的矢量并且想知道第 4 个位置为空,我该怎么做?

vx <- c(1, 2, 3, NULL, 5)

is.null() returns 仅 FALSE:

is.null(vx)
# [1] FALSE

我想得到:

 FALSE FALSE FALSE TRUE FALSE

如评论中所述,NULL不会出现在length(vx)中。它是 R 中用于未定义值的特殊对象。来自 CRAN 文档:

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

但是你的问题仍然可以有关于列表的学习机会。它会出现在那里。如:

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

尝试在非常大的数据集中识别 NULL 值对于新手 R 用户来说可能很棘手。有多种不同的技术,但这里有一种在我需要时对我有用。

!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

如果有字符,则替换为 is.character 或任何适用的 class。

可能有人(比如我)会来找 is.null(),真的需要 is.na()。如果是这样,提醒自己(像我一样)R 有一个 NULLNA 对象。 NULL 表示没有值,而 NA 表示该值未知。如果您要查找值向量中的缺失值,您可能要查找的是 is.na().