r中具有数组的子集矩阵 [英] Subset matrix with arrays in r
问题描述
这可能是相当基本的,但我还没有找到简单的解决方案.
It is probably fairly basic but I have not found an easy solution.
假设我有一个三维矩阵:
Assume I have a three-dimensional matrix:
m <- array(seq_len(18),dim=c(3,3,2))
,我想用索引数组对矩阵进行子集处理:
and I would like to subset the matrix with the arrays of indexes:
idxrows <- c(1,2,3)
idxcols <- c(1,1,2)
获取位置(1,1)
,(2,1)
和(3,2)
的数组,即:
obtaining the arrays in position (1,1)
,(2,1)
and (3,2)
, that is:
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 10 14 18
我尝试了m[idxrows,idxcols,]
,但是没有任何运气.
I have tried m[idxrows,idxcols,]
but without any luck.
反正有做吗(显然没有使用for循环)?
Is there anyway to do it (without obviously using a for loop)?
推荐答案
不确定 extract 语法是否内置任何简单的方法,但是您可以使用mapply
解决此问题:
Not sure if there is any easy built in extract syntax, but you can work around this with mapply
:
mapply(function(i, j) m[i,j,], idxrows, idxcols)
# [,1] [,2] [,3]
#[1,] 1 2 6
#[2,] 10 11 15
或更复杂的是,创建一个索引矩阵,其列与原始数组的尺寸匹配:
Or slightly more convoluted, create a index matrix whose columns match the dimensions of the original array:
thirdDim <- dim(m)[3]
index <- cbind(rep(idxrows, each = thirdDim), rep(idxcols, each = thirdDim), 1:thirdDim)
matrix(m[index], nrow = thirdDim)
# [,1] [,2] [,3]
#[1,] 1 2 6
#[2,] 10 11 15
这篇关于r中具有数组的子集矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!