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.
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)
. 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
Another (ugly) approach would be 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.