问题
I'm trying to manually increment the i variable when a condition is met.
for(i in 1:x){
if(condition){
i <- i + 2
}
}
When debugging, the (i<-i+2) line is definitely being run, but i still only increments by 1, instead of 3. (+2 from the line and an additional +1 from the auto increment)
How can I increment while I'm within the loop?
回答1:
So essentially you want to skip a few loop iterations based on a condition. It's a design choice that's rightfully frowned upon, but if you must, you need next
. The following code skips the third, fifth and seventh iteration:
for(i in 1:10){
if(i %in% c(3,5,7)){
next
}
print(i)
}
Say you need to increment with 3 based on a certain condition, then you can use a temporary variable that helps you skip a number of steps. Note that this does go through every iteration, it just breaks out of the iteration in time:
skip <- 0 # the temporary variable helping us keeping track of the iterations
for(i in 1:10){
if(i == 5){ # the condition that causes the skip
skip <- 3
}
if(skip > 0){ # the control that skips as long as necessary
skip <- skip - 1
next
}
print(i)
}
回答2:
When you run the loop, the value of the variable i
is stored in tmp*
. This means that whenever we reach the top the loop, i
resets. For example
for(i in 1:2){
message(i)
i <- 10
message(i)
}
#1
#10
#2
#10
To get what you want, you could have something like:
k =1
for(i in 1:10){
if(condition) k <- k + 2
}
回答3:
Once the sequence is created, you pretty much lose a lot of control over looping. In cases like this, I change it into a while loop and then do the conditional incrementing/decrementing at the end of the loop.
回答4:
I'm agree with joris-meys, it's "frowned upon". But... A more simple approach is:
for(i in (0:3)*2+1){
cat(i," ")
}
or
for(i in (1:4)){
cat(i," ")
}
回答5:
for(i in seq(0, 10, 2) ){
print(i)
}
you can do this..
来源:https://stackoverflow.com/questions/39556911/r-how-to-increment-the-incrementing-variable-within-a-for-loop