在R中的for循环中追加数组

时间:2016-04-27 15:51:20

标签: arrays r for-loop append

我尝试在for循环中追加一个数组。 但是在每次迭代时,我的循环都会被覆盖。 我该怎么解决呢。

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
  }

结果:

[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

上次迭代时的预期结果:

[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 个答案:

答案 0 :(得分:1)

尝试以下方法:

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)
}

如果你提前知道数组的大小,就像在第二行中那样为它预分配空间要高效得多。