How is TRUE interpreted when used as matrix index?

前端 未结 2 748
野趣味
野趣味 2021-01-21 01:43

I saw some (bad) code somewhere which turned out to call a function which executed mymatrix[TRUE] along the way. It turns out, at least in the samples I tested, t

2条回答
  •  野的像风
    2021-01-21 01:57

    Logical indices tell R which elements to include or exclude.

    You have three options:

    TRUE, FALSE, NA
    

    They serve to indicate whether or not the index represented in that position should be included. In other words:

      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)_
    

    For example:

    x <- 1:6
    x[ c(TRUE, FALSE, TRUE, NA, TRUE, FALSE)]
    #  [1]  1  3 NA  5
    

    However, standard recycling rules apply. So in the previous example, if we drop the last FALSE, the index vector is recylced, the first element of the index is TRUE, and hence the 6th element of x is now included

    x <- 1:6
    x[ c(TRUE, FALSE, TRUE, NA, TRUE       )]
    #  [1]  1  3 NA  5  6
    

    Multi dimensional x

    The above holds for any object that can be subseted using [, not just vectors.

    If x is multidimensional, we can use logical indecies on one orr all of the dimensions, or even a logical matrix as an matrix-index.

    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) ]
    

    Single dimension indexing of a multi-dimensional object.

    The catch is that matricies can be indexed not only by their dimensions, but also by their specific elements:

    x[7]
    # [1] 7
    

    Combining this fact, with R's recycling rules, we get the result referenced in the OP.
    That is, x[TRUE] is the equivalent of x[ rep(TRUE, length(x)) ], which is the equivalent of 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
    

提交回复
热议问题