[英]for loop with if else statement in R
I know lots of people have posted about this, and I did look through the answers to write my code, but it's still not working... Can someone point out where i'm doing wrong please? 我知道很多人都发布了有关此内容的信息,我确实仔细阅读了答案以编写我的代码,但是仍然无法正常工作……有人可以指出我做错了什么吗? many thanks in advance!
提前谢谢了!
for(j in 1:1000){
for(i in 1:52){
if (i == 1){
r.sims[i,] <- r.sims[1]
}
else if (i == 2){
r.sims[i,] <- r.sims[2]
}
else (i > 2){
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
i have the following errors 我有以下错误
Error: unexpected '{' in:
" }
else (i > 2){"
> r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
Error in r.sims[i, ] <- r.sims[i - 1, ] * ar1 + r.sims[i - 2, ] * ar2 + :
replacement has length zero
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>
> }
Error: unexpected '}' in " }"
>
You seem to misunderstand the concept of else
. 您似乎误解了
else
概念。
else
covers all cases that didn't match previous if
or else if
statements. else
覆盖所有与先前的if
或else if
语句不匹配的情况。 Therefore, you cannot specify any condition for else
. 因此,您不能为
else
指定任何条件。
To cover all cases where i
is not 1
or 2
simply use else
, without any ()
brackets. 要覆盖所有
i
不是1
或2
只需使用else
,而不用任何()
括号。
If you want to have a condition, use else if (condition)
. 如果您想要一个条件,请使用
else if (condition)
。
Without understanding what your code is supposed to do, I have nevertheless made an example of how you might fix your script. 在不了解您的代码应该做什么的情况下,我还是举了一个例子说明如何修复脚本。 I think the key is that you need to supply curly brackets
{...}
following your else
statement in order for it to consider the following code. 我认为关键是您需要在
else
语句后提供大括号{...}
,以便它考虑以下代码。
r.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
e.sims <- matrix(runif(52)*100, nrow=52, ncol=100)
ma1 <- 1
ar1 <- 2
ar2 <- 3
for(j in 1:1000) {
for(i in 1:52) {
if (i == 1) {
r.sims[i,] <- r.sims[1]
} else {
if(i == 2) {
r.sims[i,] <- r.sims[2]
} else {
if(i > 2) {
r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.