Reputation: 3396
I try to append an array in a for loop. However at each iteration my loop gets overwriten. How can I solve that.
rnormRdn <- matrix() #init empty matrix set.seed(1234)
set.seed(1234)
for(i in 1:3){
rnormRdn <- matrix(rnorm(n = 4), nrow = 2, ncol = 2)
print("New random matrix that should be appended is:")
print(rnormRdn)
appendMat <- array(data = rnormRdn, dim = c(2,2,i))
print("New random matrix not correctly apended on after first iteration:")
print(appendMat)
i <- i+1
}
Result:
[1] "New random matrix that should be appended is:"
[,1] [,2]
[1,] -1.2070657 1.084441
[2,] 0.2774292 -2.345698
[1] "New random matrix not correctly apended on after first iteration:"
, , 1
[,1] [,2]
[1,] -1.2070657 1.084441
[2,] 0.2774292 -2.345698
[1] "New random matrix that should be appended is:"
[,1] [,2]
[1,] 0.4291247 -0.5747400
[2,] 0.5060559 -0.5466319
[1] "New random matrix not correctly apended on after first iteration:"
, , 1
[,1] [,2]
[1,] 0.4291247 -0.5747400
[2,] 0.5060559 -0.5466319
, , 2
[,1] [,2]
[1,] 0.4291247 -0.5747400
[2,] 0.5060559 -0.5466319
[1] "New random matrix that should be appended is:"
[,1] [,2]
[1,] -0.5644520 -0.4771927
[2,] -0.8900378 -0.9983864
[1] "New random matrix not correctly apended on after first iteration:"
, , 1
[,1] [,2]
[1,] -0.5644520 -0.4771927
[2,] -0.8900378 -0.9983864
, , 2
[,1] [,2]
[1,] -0.5644520 -0.4771927
[2,] -0.8900378 -0.9983864
, , 3
[,1] [,2]
[1,] -0.5644520 -0.4771927
[2,] -0.8900378 -0.9983864
Expected result at last iteration:
[1] "New random matrix not correctly apended on after first iteration:"
, , 1
[,1] [,2]
[1,] -1.2070657 1.084441
[2,] 0.2774292 -2.345698
, , 2
[,1] [,2]
[1,] 0.4291247 -0.5747400
[2,] 0.5060559 -0.5466319
, , 3
[,1] [,2]
[1,] -0.5644520 -0.4771927
[2,] -0.8900378 -0.9983864
Upvotes: 1
Views: 7242
Reputation: 38500
Try the following:
set.seed(1234)
# initialize array, giving dimensions
myArray <- array(0, dim=c(2,2,3))
for(i in 1:3){
rnormRdn <- matrix(rnorm(n = 4), nrow = 2, ncol = 2)
print("New random matrix that should be appended is:")
print(rnormRdn)
myArray[,,i] <- rnormRdn
print("New random matrix not correctly apended on after first iteration:")
print(myArray)
}
If you know the size of the array ahead of time it is much more efficient to preallocate the space for it as I did in the second line.
Upvotes: 1