从矩阵列表中获取选定的矩阵列 [英] Getting selected matrix columns from a list of matrices
问题描述
我有一个尺寸相同的矩阵列表,例如:
I have a list of matrices with identical dimensions, for example:
mat.list=rep(list(matrix(rnorm(n=12,mean=1,sd=1), nrow = 3, ncol=4)),3)
我正在寻找一种从列表中的每个矩阵中检索列的有效方法,其中每个矩阵中感兴趣的列索引由向量指定.例如,对于此向量的列索引:
I'm looking for an efficient way to retrieve a column from each matrix in the list where the column index of interest from each matrix is specified by a vector. For example, for this vector of column indices:
idx.vec=c(3,2,3)
我想从矩阵1中获得第3列,从矩阵2中获得第2列,并从矩阵3中获得第3列,作为一个矩阵,这样该矩阵维就是列表中矩阵的行数乘以列表中的矩阵.
I would like to obtain column 3 from matrix 1, column 2 from matrix 2, and column 3 from matrix 3, as a matrix so that this matrix dimensions are the number of rows of the matrices in the list by the number of matrices in the list.
因此,对于此示例,结果将是:
For this example the result would therefore be:
cbind(mat.list[[1]][,3],mat.list[[2]][,2],mat.list[[3]][,3])
[,1] [,2] [,3]
[1,] 1.4852810 1.305448 1.4852810
[2,] 1.8647327 -1.237507 1.8647327
[3,] -0.0416013 2.156055 -0.0416013
推荐答案
一种可能的方法是mapply('[', mat.list, TRUE, idx.vec)
.诀窍是使用'['
进行子设置,并使用TRUE
作为选择所有行的参数.运作方式如下:
One possible approach would be mapply('[', mat.list, TRUE, idx.vec)
. The trick is to use '['
for subsetting and TRUE
as an argument to select all the rows. Here is how it works:
'['(matrix(1:4, ncol = 2), TRUE, 2)
# [1] 3 4
这篇关于从矩阵列表中获取选定的矩阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!