【问题标题】:R: Use an n-dimensional array as indices to subset an n+1 dimensional arrayR:使用 n 维数组作为索引来子集 n+1 维数组
【发布时间】:2016-09-28 01:03:55
【问题描述】:

我有一个 (n, m, p) 值数组和一个 (n, m) 介于 1 和 p 之间的整数数组,我想使用整数作为索引来选择不规则 (n, m) 子集的值。

for(i in 1:dim(values)[1]) {  
 for(j in 1:dim(values)[2]) {  
  slice[i, j] <- values[i, j, indices[i, j]]  
 }  
}

在 R 中是否有一种直观的内置方法可以做到这一点,最好不要展平?如果有任意数量的维度(n1,...,nk,p)怎么办?

【问题讨论】:

  • 请包括样本数据以及预期输出

标签: arrays r subset


【解决方案1】:

我试图概括它。

# example values
k <- 3    # dim=c(n1, n2, ..., nk)
n1 <- 5; n2 <- 6;  n3 <- 4; p <- 5
set.seed(1); values <- array(sample(n1*n2*n3*p), dim = c(n1, n2, n3, p))
set.seed(1); indices <- array(sample(p, n1*n2*n3, replace = T), dim = c(n1, n2, n3))

# do +1 to last dim and put indices into it (to enable apply() to get both information).
values2 <- array(values, dim=c(n1, n2, n3, p+1))
values2[,,,p+1] <- indices

   values[1,1,1,]  # [1] 160 477 111  27 569
   indices[1,1,1]  # [1] 2
   values2[1,1,1,] # [1] 160 477 111  27 569   2  # last values is index (value2[1,1,1,p+1])
   values2[1,1,1,][values2[1,1,1,p+1]]  # 477

# using apply(), get the values with all combination of n1, ..., nk
slice2 <- apply(values2, 1:k, function(x) x[x[p+1]])

   # check just to be sure
   slice <- array(NA, dim = c(n1, n2, n3))
   for(a in 1:n1) for(b in 1:n2) for(c in 1:n3) {
     slice[a, b, c] <- values[a, b, c, indices[a, b, c]] }

   identical(slice, slice2)  # [1] TRUE  # no problem

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多