将值存储在For循环中 [英] Store values in For Loop

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

问题描述

我在R中有一个for循环,我想在其中存储每次计算的结果(对于所有循环的值).在for循环中,调用了一个函数,此刻输出被存储在变量r中.但是,这在每个连续的循环中都将被覆盖.我该如何通过函数存储每个循环的结果并随后访问它?

I have a for loop in R in which I want to store the result of each calculation (for all the values looped through). In the for loop a function is called and the output is stored in a variable r in the moment. However, this is overwritten in each successive loop. How could I store the result of each loop through the function and access it afterwards?

谢谢

示例

for (par1 in 1:n) {
var<-function(par1,par2)
c(var,par1)->var2
print(var2)

因此print返回var2的每个实例,但是在var2中仅保存了最后n个值.是否有任何方法可以获取数据数组或其他内容?

So print returns every instance of var2 but in var2 only the value for the last n is saved..is there any way to get an array of the data or something?

推荐答案

初始化一个空对象,然后通过索引分配值

initialise an empty object and then assign the value by indexing

a <- 0
for (i in 1:10) {
     a[i] <- mean(rnorm(50))
}

print(a)



要包括一个具有两个输出变量的示例,在最基本的情况下,请创建一个空矩阵,其中的列数与您的输出参数相对应,并且行数与迭代次数相匹配.然后通过索引for循环中的行位置,将输出保存在矩阵中:

To include an example with two output variables, in the most basic case, create an empty matrix with the number of columns corresponding to your output parameters and the number of rows matching the number of iterations. Then save the output in the matrix, by indexing the row position in your for loop:

n <- 10
mat <- matrix(ncol=2, nrow=n)

for (i in 1:n) {
    var1 <- function_one(i,par1)
    var2 <- function_two(i,par2)
    mat[i,] <- c(var1,var2)
}

print(mat)

迭代编号i对应于mat对象中的行号.因此,无需明确跟踪它.

The iteration number i corresponds to the row number in the mat object. So there is no need to explicitly keep track of it.

但是,这只是为了说明基本知识.了解了以上内容后,使用@eddi提供的优雅解决方案会更有效,尤其是在处理许多输出变量的情况下.

这篇关于将值存储在For循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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