简体   繁体   English

在执行循环时存储数组

[英]Store array while executing for loop

I have a function which is executed 200 times like this 我有一个像这样执行200次的函数

for (l in 1:200) {
fun.ction(paramter1=g, paramter2=h)$element->u[z,,]
}

u is an array: u是一个数组:

u<-array(NA, dim=c(2000,150,7))

of which I know it should have the right format. 我知道其中的格式应该正确。 The element of func.tion is also an array which has the same dimensions. func.tion的元素也是具有相同维度的数组。 Hence, is there some way to fill the array u in each of the 200 runs with the array resulting from fun.ction()$element ? 因此,是否有某种方法可以将fun.ction()$element生成的数组填充到200个运行的数组u中? I tried to use indexing via a list ( u[[z]] ). 我试图通过列表( u[[z]] )使用索引。 It saves the array but as a list so that I can't access the elements afterwards which I would need to. 它保存数组,但将其保存为列表,以便以后无法访问需要的元素。 I appreciate any help. 感谢您的帮助。

I am not sure what it is that you want, but if you just want to store 200 arrays of dimensions (2000,150,7) you can just make another array with a fourth dimension of 200. 我不确定您想要的是什么,但是如果您只想存储200个维数数组(2000,150,7),则可以制作另一个维数为200的数组。

storage.array <- array(dim=c(2000,150,7, 200))

And then store your (2000, 150, 7) arrays in the fourth dimension: 然后将您的(2000,150,7)数组存储在第四维中:

for (i in 1:200){ 
                storage.array[,,,i] <- 
                                     fun.ction(paramter1=g, paramter2=h)$element}

Then you can access each of the ith array by: 然后,您可以通过以下方式访问每个ith数组:

storage.array[,,,i]

But I guess that will be too big an array for R to handle, at least it is in my computer. 但是我想对于R来说,它将是一个太大的数组,至少在我的计算机中是如此。

An example that you can easily reproduce with smaller arrays: 您可以使用较小的数组轻松重现一个示例:

storage.array <- array(dim=c(20,2,7, 200))

fun.ction <- function(parameter1, parameter2){
  array(rnorm(140, parameter1, parameter2), dim=c(20,2,7))
}

for (i in 1:200){
  storage.array[,,,i]<- fun.ction(10, 10)
}

But as Roland and Thomas have said, you should make your code reproducible and define correctly what you want, so it is easier to answer without trying to guess what your problem is. 但是正如Roland和Thomas所说的那样,您应该使代码具有可重现性,并正确定义所需的内容,因此在不试图猜测问题出在哪里的情况下,更容易回答。

Best regards 最好的祝福

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM