简体   繁体   中英

How to combine four vectors into three dimensional array?

a <- 1:6;
b <- seq(0.2,8,length.out = 6)
set.seed(1)
d <- runif(6, 0, 1)
e <- rnorm(6, 0, 1)

How do I get the following result: three dimensional array, dim = c(2, 2, 6) , formed by 6 matrix. The i-th matrix is composed by a[i], b[i], d[i], e[i].

Here is a method using rbind . This works because R stores matrices by column, so that we can use rbind to store values of corresponding values of a, b, d, and e together prior to storing in the array.

myArray <- array(rbind(a, b, d, e), c(2, 2, 6))

The first two Z values are

myArray[,,1:2]
, , 1

     [,1]      [,2]
[1,]  1.0 0.2655087
[2,]  0.2 1.5952808

, , 2

     [,1]      [,2]
[1,] 2.00 0.3721239
[2,] 1.76 0.3295078
array_test <- array(,c(2, 2, 6)) 
 for(i in 1:6){
      array_test[,,i] <- matrix(c(a[i],b[i],d[i],e[i]), ncol = 2, nrow = 2)
 }

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.

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