当我尝试用另一个矩阵索引一个矩阵时,我在 R 中遇到了一些奇怪的行为。我在使用 2 列矩阵进行索引时遇到了下标越界的错误,但在使用四列矩阵时却没有遇到这种情况。请参阅以下可重现的代码。任何见解将不胜感激!
这个
data <- matrix(rbinom(100, 1, .5), nrow = 10)
idx <- cbind(1:50, 51:100)
data[idx]
结果:
Error in data[idx] : subscript out of bounds
但是
data[cbind(idx,idx)]
有效。
我的 session 信息:
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin15.5.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)
最佳答案
?'['
:
When indexing arrays by
[
a single argumenti
can be a matrix with as many columns as there are dimensions ofx
; the result is then a vector with elements corresponding to the sets of indices in each row ofi
.
何时出现下标越界错误一目了然; data
没有 50 行和 100 列。
第二个示例中发生的情况是,索引矩阵只是被视为向量,因为它的列数多于被索引的矩阵的维度,并且正在提取元素c(1:100, 1:100)
来自数据
。
这更容易看到
m <- matrix(1:100, ncol = 10, byrow = TRUE)
并使用cbind(idx, idx)
进行索引给出
> m[cbind(idx,idx)]
[1] 1 11 21 31 41 51 61 71 81 91 2 12 22 32 42 52 62 72
[19] 82 92 3 13 23 33 43 53 63 73 83 93 4 14 24 34 44 54
[37] 64 74 84 94 5 15 25 35 45 55 65 75 85 95 6 16 26 36
[55] 46 56 66 76 86 96 7 17 27 37 47 57 67 77 87 97 8 18
[73] 28 38 48 58 68 78 88 98 9 19 29 39 49 59 69 79 89 99
[91] 10 20 30 40 50 60 70 80 90 100 1 11 21 31 41 51 61 71
[109] 81 91 2 12 22 32 42 52 62 72 82 92 3 13 23 33 43 53
[127] 63 73 83 93 4 14 24 34 44 54 64 74 84 94 5 15 25 35
[145] 45 55 65 75 85 95 6 16 26 36 46 56 66 76 86 96 7 17
[163] 27 37 47 57 67 77 87 97 8 18 28 38 48 58 68 78 88 98
[181] 9 19 29 39 49 59 69 79 89 99 10 20 30 40 50 60 70 80
[199] 90 100
与
相同m[c(idx[,1], idx[,2], idx[,1], idx[,2])]
或者具体来说,
m[c(1:50, 51:100, 1:50, 51:100)]
关于r - 在 R 中用另一个矩阵索引一个矩阵 - 索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469051/