本文介绍了在 R 中对多维数组进行矩阵索引时,有没有办法选择一个维度的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组,我(终于)知道我可以用一个矩阵对其进行子集化,该矩阵的列数与数组中的维数一样多.但是我需要在此过程中跳过一个维度,而不是获取/设置该维度的一个元素,而是获取/设置所有元素.怎么做?

I have a multidimensional array, and I (finally) know I can subset it with a matrix, which has as many columns as there are dimensions in the array. But I need to skip a dimension in the process, to get/set not one element of that dimension, but all of them. How to?

array5d[matrix(c(3,15,2,7,9),1)]

相当于

array5d[3,15,2,7,9]

但是基于矩阵的等价物是什么

but what is the matrix-based equivalent of

array5d[ ,15,2,7,9]

这里的目标是能够用一组单独生成的向量值对数组进行子集化.我并不总是需要在第一个维度保持开放的情况下进行子集化,这个(或者更确切地说,这些)因情况而异.我有一个非常难看的 eval(str2lang(paste0(...))) 解决方案,但我真的想要一个更健康的方法

The goal here is to be able to subset an array with values of a bunch of vectors, that are generated separately. I don't always need to subset with the first dimension left open, this (or rather, these) changes from case to case. I have a very ugly solution with eval(str2lang(paste0(...))), but I would really like a healthier approach

推荐答案

更简单的可重现示例:

array3d <- array(1:27,dim=c(3,3,3))
x <- array3d[,1,1]

@user2957945 在评论中指出,将索引向量的空白"元素设置为 TRUE 将允许 do.call('[',...) 选择所有元素来自那个维度.

In the comments @user2957945 points out that setting the 'blank' elements of the index vector to TRUE will allow do.call('[',...) to select all of the elements from that dimension.

i <- list(TRUE, 1, 1);  do.call('[', c(list(array3d), i))


上一个(次优)答案:


Previous (suboptimal) answer:

我不知道是否有更简单/更好的方法,但这无需使用 str2lang/eval/etc.:

I don't know if there's a simpler/better way, but this works without using str2lang/eval/etc.:

i <- c(NA,1,1)  ## NA denotes "get all elements from this dimension"
getfun <- function(a,i) {
   i <- as.list(i)
   for (j in seq_along(i)) {
     if (all(is.na(i[[j]]))) i[[j]] <- seq(dim(a)[j])
   }
   v <- as.matrix(do.call(expand.grid,i))
   a[v]
}
getfun(array3d,i)

这篇关于在 R 中对多维数组进行矩阵索引时,有没有办法选择一个维度的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:26