如何检测向量中的空值 [英] How to detect null values in a vector

查看:80
本文介绍了如何检测向量中的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Whats the best way to detect null values in a vector?

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

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() 只返回 FALSE:

is.null(vx)
# [1] FALSE

我想得到:

 FALSE FALSE FALSE TRUE FALSE

推荐答案

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

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 代表 R 中的空对象:它是一个保留字.NULL 是通常由值未定义的表达式和函数返回.

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)

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

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

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

If there are characters, then substitute in is.character or whatever class applies.

这篇关于如何检测向量中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆