in R, the arguments of "for loop"
Could anyone please tell me what is wrong with the R code below:
i = 1.001
#make SAV and STO become vector
开发者_如何学JAVASAV = c()
STO = c()
#set the initial values for the vector
SAV[1] = 0
STO[1] = 100
for (t in 2:1000) {
if ((price[t]>9.9)&(price[t]<10.1)&(SAV[t-1]!=0))
SAV[t]=SAV[t-1]*i
STO[t]=0
}
for (t in 2:1000) {
if ((price[t]>9.9)&(price[t]<10.1)&(SAV[t-1]=0))
STO[t] = STO [t-1]
SAV[t] = 0
}
SAV
STO
What I am trying to do is to find vector for both SAV and STO.
I would try something like the following. Modify it to be consistent with your program's logic
for (t in 2:1000) {
if ((price[t]>9)&(price[t]<10)) {
# values for STO,SAV when price in the interval and SAV[t-1]!=0
if (SAV[t-1]!=0) {
SAV[t]=SAV[t-1]*i
STO[t]=0
}
# values for STO,SAV when price in the interval and SAV[t-1]==0
else {
STO[t] = STO[t-1]
SAV[t] = 0
}
}
# values for STO,SAV when price not in the interval
else {
STO[t] = STO[t-1]
SAV[t] = 1
}
}
I think you're overwriting the vectors STO and SAV each iteration. Hard to tell though because the price vector hasn't been declared. Try initializing STO and SAV as vectors of the desired length, rather than 0-length vectors:
SAV = matrix(0,1,1000)
STO = matrix(0,1,1000)
I'm not really good a R, but maybe the arrays start at 0? (instead at 1)
SAV[1] = 0
STO[1] = 100
==>
SAV[0] = 0
STO[0] = 100
And my second guess is regarding the if conditions in the for-loops. I would put brackets upon the whole expression, something like this.
for (t in 2:1000) {
if ((price[t]>9.9)&(price[t]<10.1)&(SAV[t-1]=0)) {
STO[t] = STO [t-1]
SAV[t] = 0
}
}
I hardly think it could help, but it's worth a try ;)
Edit:
Try to use SAV[t-1]==0
instead of SAV[t-1]=0
in your if condition ...
Edit 2:
Also try to use the && operator instead of the & one ...
精彩评论