了解逻辑索引的行为

Understanding the behaviour of Logical Indices

我有以下片段

x <- 20:1
x
x[c(T, F, NA)] <- 1
x
[1]  1 19 18  1 16 15  1 13 12  1 10  9  1  7  6  1  4  3  1  1

我不明白结果是如何产生的。我认为 T = 1、F = 0 并且 NA 也被视为假(因此 NA = 0)。

所以我期望得到以下结果:

[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

谁能给我解释一下 R 在做什么?这是某种隐藏的 "If ... then"-语句吗? 20, 17, 14, 11, 8... 显然是 True 但为什么呢?

您可以先查看,

x[T]
#[1] 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1

然后

x[F]
#integer(0)

还要检查,

x[NA]
# [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

R 使用循环索引(不确定这个词是否正确)

现在,当你这样做时

x[c(T, F, NA)]

它给出,

#[1] 20 NA 17 NA 14 NA 11 NA  8 NA  5 NA  2

它打印所有 T 值,忽略所有 F 值并给出 NA 代替所有 NA 值。

现在当你分配

x[c(T, F, NA)] <- 1

只有索引为T的索引被替换为1,其余的都是原样,给出

#[1]  1 19 18  1 16 15  1 13 12  1 10  9  1  7  6  1  4  3  1  1

正如@alexis_laz 所评论的那样,NAs 引用了文档

When extracting, a numerical, logical or character NA index picks an unknown element and so returns NA in the corresponding element of a logical, integer, numeric, complex or character result, and NULL for a list.

When replacing (that is using indexing on the lhs of an assignment) NA does not select any element to be replaced. As there is ambiguity as to whether an element of the rhs should be used or not, this is only allowed if the rhs value is of length one

总而言之,在提取 x[NA] 时,它 returns 为 NA,而在替换 x[NA] <- 时,它不会 select 任何要替换的元素。