当用作矩阵索引时,如何解释TRUE?

Car*_*oft 3 r

我在某个地方看到了一些(坏)代码,这些代码最终调用了一个mymatrix[TRUE]沿途执行的函数.事实证明,至少在我测试的样本中,这被解释为选择矩阵的所有元素.显然[不是强迫TRUE1,因为当时我只得到第一个元素中返回,而不是整个矩阵. mymatrix[FALSE]回报numeric(0).有人能解释一下[这里到底在做什么吗?

Ric*_*rta 7

Logicalindices指出R要包含或排除的元素.

你有三个选择:

TRUE, FALSE, NA
Run Code Online (Sandbox Code Playgroud)

它们用于表明是否应包括在该位置表示的指数.换一种说法:

  TRUE  == "Include the elment at this index"
  FALSE == "Do not include the element at this index"
  NA    == "Return NA instead of this index"  _(losely speaking)_
Run Code Online (Sandbox Code Playgroud)

例如:

x <- 1:6
x[ c(TRUE, FALSE, TRUE, NA, TRUE, FALSE)]
#  [1]  1  3 NA  5
Run Code Online (Sandbox Code Playgroud)

但是,适用标准回收规则.所以在前面的例子中,如果我们删除最后一个FALSE,则索引向量被重新定义,索引的第一个元素是TRUE,因此现在包括6th元素x

x <- 1:6
x[ c(TRUE, FALSE, TRUE, NA, TRUE       )]
#  [1]  1  3 NA  5  6
Run Code Online (Sandbox Code Playgroud)

多维度 x

以上内容适用于任何可以使用子对象的对象[,而不仅仅是向量.

如果x是多维的,我们可以在一个或所有维度上使用逻辑indence,或者甚至将逻辑矩阵用作矩阵索引.

x <- matrix(1:12, nrow=3, ncol=4)

# using logical vectors on both dims
#   returns intersection of 2nd row and 3rd column
x[c(TRUE, FALSE, FALSE),  c(FALSE, FALSE, TRUE, FALSE)]
# [1] 7

# Same value
x[c(TRUE, FALSE, FALSE),  3]
# [1] 7

# return a checkerboard pattern, using a logical matrix as an index
x[ matrix(c(TRUE, FALSE), nrow=3, ncol=4) ]
Run Code Online (Sandbox Code Playgroud)

多维对象的单维索引.

问题在于,matricies不仅可以通过其维度进行索引,还可以通过其特定元素进行索引:

x[7]
# [1] 7
Run Code Online (Sandbox Code Playgroud)

结合这一事实和R我们的回收规则,我们得到OP中引用的结果.
也就是说, x[TRUE]相当于x[ rep(TRUE, length(x)) ],相当于return every element of x

x[TRUE]
# [1]  1  2  3  4  5  6  7  8  9 10 11 12

x[TRUE, ,drop=FALSE]
#        [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12
Run Code Online (Sandbox Code Playgroud)


Mat*_*rde 6

当用作索引时,逻辑向量被再循环以匹配向量的长度.例如,mymatrix[c(TRUE, FALSE)]会给你所有其他元素.