append array in a for loop in R

送分小仙女□ 提交于 2019-12-12 00:42:58

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/36894818/append-array-in-a-for-loop-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!