R 选择数据帧子集时出现意外的NAs行

R 选择数据帧子集时出现意外的NAs行,r,R,从数据帧中选择数据子集时,我得到的行完全由原始数据帧中不存在的NA值组成。例如: example.df[example.df$census_tract == 27702, ] 返回: census_tract number_households_est NA NA NA 23611 27702 2864 第一排NAs来自哪里?为什么即使example.df$census

从数据帧中选择数据子集时,我得到的行完全由原始数据帧中不存在的NA值组成。例如:

example.df[example.df$census_tract == 27702, ]
返回:

      census_tract number_households_est
NA              NA                    NA
23611        27702                  2864

第一排NAs来自哪里?为什么即使
example.df$census\u tract!=27702该行的代码?

这是因为缺少观察值

> sum(is.na(example.df$census_tract))
[1] 1
> example.df[which(is.na(example.df$census_tract)), ]
   census_tract number_households_est
64           NA                    NA
=
计算第64行时,它会给出
NA
,因为默认情况下,我们无法知道27702是否等于缺少的值。因此,结果丢失(aka
NA
)。因此,
NA
被放入用于索引目的的逻辑向量中。默认情况下,这会给出一行-
NA
,因为我们需要一行,但“我们不知道是哪一行”

正确的方法是

> example.df[example.df$census_tract %in% 27702, ]
      census_tract number_households_est
23611        27702                  2864

HTH,Luca

这也是
which
可以帮助的情况:
example.df[which(example.df$census\u tract==27702),]
谢谢。为什么
==
与NA行匹配?当您的版本报告64时,为什么它报告NA的行数?