在R中的for循环中追加数组 [英] append array in a for loop in R

查看:1189
本文介绍了在R中的for循环中追加数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在for循环中附加一个数组。
但是,在每次迭代中,我的循环都会被覆盖。
我该如何解决。

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
  }

结果:

[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


推荐答案

尝试以下:

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.

这篇关于在R中的for循环中追加数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆