yrx1702
yrx1702

Reputation: 1641

Convert list to matrix using indicator vector

I have the following list of 5x2 matrices:

l <- list(a=matrix(rnorm(10),nrow=5,ncol=2),
          b=matrix(rnorm(10),nrow=5,ncol=2),
          c=matrix(rnorm(10),nrow=5,ncol=2))

For example, the first element of this list looks like this:

$a
           [,1]       [,2]
[1,] -0.4988268  1.9881333
[2,] -0.2979064  1.5921169
[3,] -1.3783522 -1.4149601
[4,]  0.2205115  0.2029210
[5,]  1.2721645  0.2861253

I want to take this list and create a new 5x2 matrix using information from a vector v:

v <- c("a","a","b","c","b")

This vector is an indicator vector that has information on how this new matrix should be constructed. That is, take row 1 from list element a, take row 2 from list element a and so on.

One could do it through a for-loop, however, for my application this is not efficient enough and I feel there might be a more elegant solution to it. My approach:

goal <- matrix(nrow=5,ncol=2)
for(i in 1:length(v)){

  goal[i,] <- l[[v[i]]][i,]

}

goal
           [,1]       [,2]
[1,] -0.4988268 1.98813326
[2,] -0.2979064 1.59211686
[3,]  0.7715907 0.16776669
[4,]  0.2690278 0.02542766
[5,]  1.7865093 0.46361239

Thanks!

Upvotes: 0

Views: 98

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

Assuming all the list matrices have same number of row, we could use mapply and subset the matrices by name (v) and row number.

t(mapply(function(x, y) l[[x]][y, ], v, 1:nrow(l[[1]])))

#        [,1]       [,2]
#a -1.2070657  0.5060559
#a  0.2774292 -0.5747400
#b -0.7762539 -0.9111954
#c  0.4595894 -0.0151383
#b  0.9594941  2.4158352

data

set.seed(1234)
l <- list(a=matrix(rnorm(10),nrow=5,ncol=2),
          b=matrix(rnorm(10),nrow=5,ncol=2),
          c=matrix(rnorm(10),nrow=5,ncol=2))

Upvotes: 1

Related Questions