在R中,NA == NA吗? [英] in R does NA == NA?

查看:159
本文介绍了在R中,NA == NA吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

identical(NA, NA)返回TRUE,但是以下代码过滤了日期框架中的NA:

identical(NA, NA) returns TRUE, but the following code filters NA out of the date frame:

library(tidyverse)
filter(starwars, birth_year == birth_year)

如果NA等于NA,则上述 starwars 过滤的数据框应包含NA的出生年份.为什么不呢?

If NA does equal NA the starwars filtered data frame above should include birth years of NA. Why doesn't it?

推荐答案

NA是NA中的identical,但不相等.如果运行NA==NA,则响应将为NA,因为equal运算符不适用于NA.从identical文档:

NA is identical to NA, but doesn't equal it. If you run NA==NA, the response will be NA, because the equal operator doesn't apply to NAs. From the identical documentation:

对same的调用是在if和while中测试完全相等的方法 语句以及使用&&或||.在 所有这些应用程序都需要确保得到一个 逻辑值.

A call to identical is the way to test exact equality in if and while statements, as well as in logical expressions that use && or ||. In all these applications you need to be assured of getting a single logical value.

用户经常在其中使用比较运算符,例如==或!= 情况.看起来很自然,但这不是这些运算符 设计为在R中执行.它们返回一个类似参数的对象.如果你 期望x和y的长度为1,但是碰巧其中之一 否则,您将不会获得单个FALSE.同样,如果 参数是NA,结果也是NA.无论哪种情况,表达式 if(x == y)....不能按预期工作.

Users often use the comparison operators, such as == or !=, in these situations. It looks natural, but it is not what these operators are designed to do in R. They return an object like the arguments. If you expected x and y to be of length 1, but it happened that one of them was not, you will not get a single FALSE. Similarly, if one of the arguments is NA, the result is also NA. In either case, the expression if(x == y).... won't work as expected.

以及来自==的文档:

缺失值(NA)和NaN值被认为是不可比的 对他们自己,因此涉及它们的比较将始终导致不适用. 比较字符串和 一个在当前的整理语言环境中无效.

Missing values (NA) and NaN values are regarded as non-comparable even to themselves, so comparisons involving them will always result in NA. Missing values can also result when character strings are compared and one is not valid in the current collation locale.

基本原理是,在概念层面上缺失的值彼此不同.它们可能表示不同的值,但我们不知道这些值是什么.

The rationale is that missing values, at a conceptual level, are not the same as one another. They could potentially represent very different values, but we just don't know what those values are.

在这种情况下,可以选择添加| is.na(birth_year).

An alternative in this situation is to add | is.na(birth_year).

这篇关于在R中,NA == NA吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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