stevenjoe
stevenjoe

Reputation: 339

Reset Loop Variable in R

I am looping through a variable "i" in a for loop and want to reassign a value to "i" based on the outcome of an if statement. Example below.

for (i in 1:nrow(df)) {
     if (df[i, 5] > 4) {
          i <- 1
     } else {
          df[i, 5] <- df[1, 5] - 1
     }
}

The script works as expected if I manually run it multiple times, but it doesn't seem to be reassigning i correctly and/or registering it in the loop. Ideas? Suggestions? Thanks in advance!

Upvotes: 0

Views: 4817

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145765

Changing the value of i inside the loop won't change where you are in the 1:nrow(df). I think this illustrates nicely:

counter = 1
for (i in 1:3) {
    cat("counter ", counter, "\n")
    cat("i starts as ", i, "\n")
    i = 7
    cat("i is is set to ", i, "\n\n")
    counter = counter + 1
}
# counter  1 
# i starts as  1 
# i is is set to  7 
# 
# counter  2 
# i starts as  2 
# i is is set to  7 
# 
# counter  3 
# i starts as  3 
# i is is set to  7 

Maybe you should be using a while loop? I think this is what you are trying to achieve, but with no sample input, explanation, or desired output provided in your question, it's just a guess:

i <- 1
while (i <= nrow(df)) {
     if (df[i, 5] > 4) {
          i <- 1
     } else {
          df[i, 5] <- df[1, 5] - 1
          i <- i + 1
     }
}

Upvotes: 3

Related Questions