NM_
NM_

Reputation: 1999

Select elements column-wise from a matrix to create a list of new matrices in R

Suppose I have matrices u, v, w of dimension 3 x n where n > 3. So u, v, w are of the form:

> u
u11 u12 ... u1n
u21 u22 ... u2n
u31 u22 ... u3n

> v
v11 v12 ... v1n
v21 v22 ... v2n
v31 v22 ... v3n

> w
w11 w12 ... w1n
w21 w22 ... w2n
w31 w22 ... w3n

Is it possible to create a list of 3 x 3 matrices which bind u, v and w column wise in R? By this I mean that I would like to get a list of the form:

[[1]]
u11 v11 w11
u21 v21 w21
u31 v31 w31

[[2]]
u12 v12 w12
u22 v22 w22
u32 v32 w32

.
.
.


[[n]]
u1n v1n w1n
u2n v2n w2n
u3n v3n w32n

I have tried

> do.call(cbind, list=(u,v,w))

but this does not work.

Example with data

set.seed(1)
u = matrix(rnorm(15), nrow = 3)
v = matrix(rnorm(15), nrow = 3)
w = matrix(rnorm(15), nrow = 3)

> u
           [,1]       [,2]      [,3]       [,4]       [,5]
[1,] -0.6264538  1.5952808 0.4874291 -0.3053884 -0.6212406
[2,]  0.1836433  0.3295078 0.7383247  1.5117812 -2.2146999
[3,] -0.8356286 -0.8204684 0.5757814  0.3898432  1.1249309
> v
            [,1]      [,2]        [,3]        [,4]       [,5]
[1,] -0.04493361 0.8212212  0.78213630  0.61982575 -1.4707524
[2,] -0.01619026 0.5939013  0.07456498 -0.05612874 -0.4781501
[3,]  0.94383621 0.9189774 -1.98935170 -0.15579551  0.4179416
> w
           [,1]        [,2]       [,3]       [,4]       [,5]
[1,]  1.3586796 -0.05380504 -0.3942900  0.7631757  0.6969634
[2,] -0.1027877 -1.37705956 -0.0593134 -0.1645236  0.5566632
[3,]  0.3876716 -0.41499456  1.1000254 -0.2533617 -0.6887557

Desired Output:

[[1]]
-0.6264538 -0.04493361  1.3586796
 0.1836433 -0.01619026 -0.1027877
-0.8356286  0.94383621  0.3876716

[[2]]
 1.5952808 0.8212212 -0.05380504
 0.3295078 0.5939013 -1.37705956
-0.8204684 0.9189774 -0.41499456

.
.
.

[[5]]
-0.6212406 -1.4707524  0.6969634
-2.2146999 -0.4781501  0.5566632
 1.1249309  0.4179416 -0.6887557

Upvotes: 0

Views: 72

Answers (1)

user20650
user20650

Reputation: 25854

You can do this by combining the data and using array to set the dimension:

ar <- array(rbind(u, v, w), dim = c(3, 3, ncol(u))) 

If you want it in list then asplit can be used, where the array is split in the 3rd dimension

ars <- asplit(ar, 3)
ars[c(1,2,5)]
# [[1]]
#            [,1]        [,2]       [,3]
# [1,] -0.6264538 -0.04493361  1.3586796
# [2,]  0.1836433 -0.01619026 -0.1027877
# [3,] -0.8356286  0.94383621  0.3876716
# 
# [[2]]
#            [,1]      [,2]        [,3]
# [1,]  1.5952808 0.8212212 -0.05380504
# [2,]  0.3295078 0.5939013 -1.37705956
# [3,] -0.8204684 0.9189774 -0.41499456
# 
# [[3]]
#            [,1]       [,2]       [,3]
# [1,] -0.6212406 -1.4707524  0.6969634
# [2,] -2.2146999 -0.4781501  0.5566632
# [3,]  1.1249309  0.4179416 -0.6887557

Upvotes: 3

Related Questions