【发布时间】:2017-03-25 19:01:55
【问题描述】:
我想根据多个值获取 R 中 3D 数组的索引(即 arr[x,y,z])。具体来说,使用第一个 z 维度对第二个 z 维度中的值进行子集化。这是一个例子:
# create example array
> m1 <- matrix(c(rep("a",5), rep("b",5), rep("c",5)), nr = 5)
> m2 <- matrix(c(rep(100, 5), rep(10, 5), rep(10, 5)), nr = 5)
> arr <- array(c(m1, m2), dim = c(dim(m1), 2))
#use which() to return the indices in m2 that correspond to indices with
#"a" and "c" values in m1. This does not work as expected.
> ac.ind <- which(arr[,,1] %in% c("a", "c"), arr.ind = T)
> ac.ind
[1] 1 2 3 4 5 11 12 13 14 15
which() 返回 m1 中对应于“a”和“c”的位置向量,而不是矩阵索引((x,y) 位置)。我希望 ac.ind 返回:
row col
[1,] 1 1
[2,] 2 1
[3,] 3 1
[4,] 4 1
[5,] 5 1
[1,] 1 3
[2,] 2 3
[3,] 3 3
[4,] 4 3
[5,] 5 3
如果我做一个更简单的 which() 子集,它确实会返回索引:
#use which to return indices in m2 that correspond to only "a" in m1
>a.ind <- which(arr[,,1] == c("a"), arr.ind = T)
>a.ind
row col
[1,] 1 1
[2,] 2 1
[3,] 3 1
[4,] 4 1
[5,] 5 1
我使用 %in% 是因为我想根据 m1 中的两个值(“a”和“c”值)进行子集化。有没有办法根据 R 中的两个值返回数组的索引?
【问题讨论】:
-
另见
?arrayInd;arrayInd(ac.ind, dim(arr)[1:2])