Subset matrix with arrays in r

不想你离开。 提交于 2019-12-11 05:46:22

问题


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)

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

I have tried m[idxrows,idxcols,] but without any luck.

Is there anyway to do it (without obviously using a for loop)?


回答1:


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


来源:https://stackoverflow.com/questions/41384466/subset-matrix-with-arrays-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!