简体   繁体   English

从矩阵列表中获取选定的矩阵列

[英]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)

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. 我想从矩阵1的第3列,矩阵2的第2列和矩阵3的第3列,作为矩阵,以便这个矩阵维度是列表中矩阵的行数乘以矩阵中的矩阵数。名单。

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

One possible approach would be mapply('[', mat.list, TRUE, idx.vec) . 一种可能的方法是mapply('[', mat.list, TRUE, idx.vec) The trick is to use '[' for subsetting and TRUE as an argument to select all the rows. 诀窍是使用'['进行子集化,使用TRUE作为参数来选择所有行。 Here is how it works: 下面是它的工作原理:

'['(matrix(1:4, ncol = 2), TRUE, 2)
# [1] 3 4

Another (ugly) approach would be lapply(mat.list, "[",,idx.vec)[[1]] : 另一个(丑陋的)方法是lapply(mat.list, "[",,idx.vec)[[1]]

> set.seed(1)
> mat.list=rep(list(matrix(rnorm(n=12,mean=1,sd=1), nrow = 3, ncol=4)),3)
> idx.vec=c(3,2,3)
> lapply(mat.list, "[",,idx.vec)[[1]]
         [,1]      [,2]     [,3]
[1,] 1.487429 2.5952808 1.487429
[2,] 1.738325 1.3295078 1.738325
[3,] 1.575781 0.1795316 1.575781

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM