I am trying to create a array with 3 dims, 2 by 2 by 4.I want to repeat the matrix 4 times to build the matrix. Quite simple but not working so far... Here is my code:
m <- array(0,c(2,2,4))
for (i in 4) {
m[,,i] <- array(1:4,c(2,2))
}
Result:
, , 1
[,1] [,2]
[1,] 0 0
[2,] 0 0
, , 2
[,1] [,2]
[1,] 0 0
[2,] 0 0
, , 3
[,1] [,2]
[1,] 0 0
[2,] 0 0
, , 4
[,1] [,2]
[1,] 1 3
[2,] 2 4
Expected result at last iteration:
, , 1
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 2
[,1] [,2]
[1,] 1 3
[2,] 2 4
, , 3
[,1] [,2]
[1,] 1 4
[2,] 2 3
, , 4
[,1] [,2]
[1,] 1 3
[2,] 2 4
CodePudding user response:
You do not need a loop to do this.
array
recycles its input so you can do this:
start_matrix <- matrix(1:4, 2, 2)
array(start_matrix, dim = c(2,2,4))