因子查找中的 NA 意外 return

Unexpected return for NA in factor lookup

我有一个因素用作查找 table。

condLookup = c(hotdog = "ketchup", ham = "mustard", popcorn = "salt", coffee = "cream")

这按预期工作 - 我输入一个 3 向量并得到一个 3 向量:

condLookup[c("hotdog", "spinach", NA)]
  hotdog      <NA>      <NA> 
"ketchup"       NA        NA 

这也是预料之中的,即使 returns 都是 NA:

condLookup[c(NA, "spinach")]
<NA> <NA> 
  NA   NA 

还有这个:

condLookup["spinach"]
<NA> 
  NA 

但这让我感到惊讶 - 我给了一个原子 NA,或两个 NA,然后我得到了一个由 4 个 NA 组成的命名向量。

condLookup[NA]
<NA> <NA> <NA> <NA> 
  NA   NA   NA   NA 
condLookup[c(NA, NA)]
<NA> <NA> <NA> <NA> 
  NA   NA   NA   NA 

显然,对于 vector2 <- condLookup[vector1],那么 vector2 的长度将与 vector1 相同,除非 vector1 中的每个元素都是不适用。在这种情况下 vector2condLookup 的长度相同。 你能解释一下这种行为吗?

NA 值是类型化的,类型很重要:c(NA,"spinach")NA 强制转换为不回收的字符:

condLookup[NA]
## <NA> <NA> <NA> <NA> 
##   NA   NA   NA   NA 

condLookup[NA_character_]
## <NA> 
##  NA

NA 的默认类型是逻辑。逻辑向量将被回收以匹配向量的长度,而字符向量将用于匹配向量的名称。来自 ?[:

Character vectors will be matched to the ‘names’ of the object

... ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent.

除了@Ben的回答——回收,?Extract还显示了以下语句:

  • Neither empty ("") nor NA indices match any names, not even empty nor missing names. If any object has no names or appropriate dimnames, they are taken as all "" and so match nothing.