【问题标题】:Return the indices of a 3D array in R based on multiple values根据多个值返回 R 中 3D 数组的索引
【发布时间】: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])

标签: arrays r


【解决方案1】:

问题是arr[,,1] %in% c("a", "c") 返回一个向量。一种方法是将其转换为matrix,其行数等于arr 的第一个维度:

ac.ind <- which(matrix(arr[,,1] %in% c("a", "c"), nrow=dim(arr)[1]), arr.ind = T)
##      row col
## [1,]   1   1
## [2,]   2   1
## [3,]   3   1
## [4,]   4   1
## [5,]   5   1
## [6,]   1   3
## [7,]   2   3
## [8,]   3   3
## [9,]   4   3
##[10,]   5   3

【讨论】:

  • 谢谢!这就是我要找的。​​span>
【解决方案2】:

类似这样,但效率不高,因为它必须遍历数据两次:

ac.ind <- which(arr[,,1] == "c" | arr[,,1] == "a" , arr.ind = T)

ac.ind

          row col
     [1,]   1   1
     [2,]   2   1
     [3,]   3   1
     [4,]   4   1
     [5,]   5   1
     [6,]   1   3
     [7,]   2   3
     [8,]   3   3
     [9,]   4   3
    [10,]   5   3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2022-01-12
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2022-01-19
    相关资源
    最近更新 更多