0

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!

stevenjoe
  • 329
  • 1
  • 4
  • 16
  • What do you mean by "doesn't seem to be reassigning correctly"? What is the behavior you are observing. It's easier to help you if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Provide us some sample input and the desired output – MrFlick Mar 23 '17 at 17:48
  • Just curious, but why would I get down votes? Assessed to be a bad question I assume? Perhaps lack of a reproducible example? – stevenjoe Mar 23 '17 at 19:16
  • Just found this. My apologies for the question then although I am very grateful for the answer. "Downvoting implies that the question isn't well-researched." – stevenjoe Mar 23 '17 at 19:19

1 Answers1

2

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
     }
}
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • Ahhhh... okay. If that is the case, I think that would be the problem. I appreciate the insight and provision of the `while` format. I will attempt a revision with `while`. Thanks for your help! – stevenjoe Mar 23 '17 at 19:13