如果已经没有任何 NA,则在特定列中查找没有 NA 的行

finding rows which don't have NA in a particular column if it already didn't have any NA

我刚刚观察到,如果我的数据框中的其中一列不包含任何 NA 值(请参阅下面的 col2)并且我在不知不觉中尝试查找不具有相应 col2 值的行作为 NA,下面代码给我一个空输出。

请参阅下面的 col1,因为它至少有一个 NA 值。 同样不适用于 col2

> col1 = c(1,1,1,1,NA)
> col2 = c(2,2,2,2,2)
> df = data.frame(col1,col2)
> df
  col1 col2
1    1    2
2    1    2
3    1    2
4    1    2
5   NA    2
> df[-which(is.na(df$col1)),]
  col1 col2
1    1    2
2    1    2
3    1    2
4    1    2
> df[-which(is.na(df$col2)),]
[1] col1 col2
<0 rows> (or 0-length row.names)

我能够让它按如下方式工作,但只是想知道上述行为是否合适?

> df[which(! is.na(df$col2)),]
  col1 col2
1    1    2
2    1    2
3    1    2
4    1    2
5   NA    2

问题不仅限于 NA。如果索引向量为空,就会发生这种情况。 希望是返回整个向量,但实际上,x[numeric(0)]x由长度为0的向量索引)returns一个空向量。

例如,考虑以下内容:

> df[ c(-1), ] # Negative indexing
  col1 col2
2    1    2
3    1    2
4    1    2
5   NA    2
> df[ c(), ] # numeric(0)
[1] col1 col2
<0 rows> (or 0-length row.names)
> df[ c(1), ] # Positive indexing
  col1 col2
1    1    2

请参阅 R inferno 中的第 8.1.13 节以获得更一般的解释和解决方法。