为什么用'[]'过滤向量元素的结果是NA,而'which'函数不返回任何NA?
下面是一个例子。
setor <- c('residencial','residencial',NA,'comercial')
setor[setor == 'residencial']
#"residencial" "residencial" NA`
setor[which(setor=='residencial')]
#[1] "residencial" "residencial"
非常感谢你的帮助!
因为当你使用 ==
相比之下,它返回 NA
为NA值。
setor == 'residencial'
#[1] TRUE TRUE NA FALSE
和子集与 NA
返回 NA
setor[setor=='residencial']
#[1] "residencial" "residencial" NA
然而,当我们使用 which
不算数 NA
的指数,并只返回 TRUE
值。
which(setor=='residencial')
#[1] 1 2
setor[which(setor=='residencial')]
#[1] "residencial" "residencial"
我们可以使用 %in%
,它返回 FALSE
凡是 NA
元素
setor %in% 'residencial'
#[1] TRUE TRUE FALSE FALSE
当我们需要子集多个元素时,它也可以使用,即
setor %in% c('residencial', 'comercial')
#[1] TRUE TRUE FALSE TRUE
这可以直接用于子集
setor[setor %in% 'residencial']
#[1] "residencial" "residencial"