简体   繁体   English

将循环结果保存在向量R中

[英]save results of loop in a vector R

I run a loop: 我运行一个循环:

N = 10
alpha = 0.05
sigma = 0.01
for (i in 0:N){
Vt10[i] = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))
}

However, Vt10 eventually outputs only 10 outcomes (doesn't include the first iteration, when i = 0 ). 但是, Vt10最终仅输出10个结果(当i = 0时不包括第一次迭代)。 How can I create a vector that would include all 11 iterations? 如何创建一个包含所有11个迭代的向量?

Answer: 回答:

N = 10
alpha = 0.05
sigma = 0.01
Vt10 = numeric(11)  ## this!
for (i in 0:N){
Vt10[i+1] = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))
}

Also, you need Vt10[i+1] , because you loop from 0 to 10, while array index should be 1 to 11. 另外,您需要Vt10[i+1] ,因为您从0循环到10,而数组索引应该是1到11。


Comment: 评论:

Your code looks like C code. 您的代码看起来像C代码。 Not only you start index from 0, but also you write a loop for this task. 您不仅从0开始索引,而且为此任务编写了一个循环。

Try: 尝试:

N = 10
alpha = 0.05
sigma = 0.01
i = 0:10
Vt10 = ((sigma^2)/(alpha^2))*((N-i)+(2/alpha))*exp(-alpha*(N-i))-(1/(2*alpha))*exp(-2*alpha*(N-i))-(3/(2*alpha))

In this situation, there is no need to predefine a vector. 在这种情况下,无需预先定义向量。 R knows you are performing element-wise computation, and will automatically assign a length-11 vector for Vt10 . R知道您正在执行逐元素计算,并将自动为Vt10分配一个长度为11的向量。

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

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