I am looking to see if there is a way to reset a for loop if a condition is satisfied in R.
For example if I have a dummy dataset and parameters:
# repeatable random numbers
set.seed(999)
# half-hourly time vector
t=seq(0,365,1/48)
# s vec initalized to zero
s = rep_len(0,length(t))
# set parameters
s[1] = 9 # initial value
s_max = 10.0
d = 1.5-cos(2*pi*(t-8/48)) rlnorm(length(t))
c = 1.9-cos(2*pi*t) rlnorm(length(t))
I have a for loop that does what I want and creates an error whenever s[i] < 0 as such:
# time step
for (i in 1:(length(t)-1)) {
if (s[i] < 0) {
print("error: outage has occurred. Increase s_max")
break
}
if (c[i] > d[i]) {
if (s[i] < s_max) {
s[i 1] = s[i] (c[i]-d[i]) # s increases
if (s[i 1] > s_max) {
s[i 1] = s_max
}
} else {
s[i 1] = s_max
}
} else {
if (s[i] > 0) {
s[i 1] = s[i] (c[i]-d[i]) # s decreases
}
}
}
However, if it fails I then have to increase s_max myself! So I was wondering if there was a way that I could set I back to 1 to start the loop again and increase s_max by 1.
if (s[i] < 0) {
i = 1
s_max = s_max 1}
And so on..
But this does not seem to work! I was wondering if there is a way or function to call that could help with this.
This example should be replicable so feel free to try it out! Let me know if you have any troubles.
Thanks!
CodePudding user response:
No, you can't modify the index in a for loop. You should use some other kind of loop. For example,
for (i in 1:(length(t)-1)) {
stuff
}
is the same as
i <- 0
while (i < (length(t) - 1)) {
i <- i 1
stuff
}
except that you are allowed to modify i in the while loop.
