Home > Software engineering >  Iterating over a changing sequence in a for loop
Iterating over a changing sequence in a for loop

Time:01-04

Suppose we have syntax as follows:

for (i in sequence) {
  ...
  sequence <- append(sequence, i, after = 3)
}

But the code seems not to work properly because sequence is not updating within the brackets. I have come up with a similar decision using while loop instead. Is it possible to use for loop anyway?

CodePudding user response:

The for loop in R only evaluates the seq value (sequence in your example) at the beginning. So changing sequence in your loop will have no effect over how many times the loop will run.

For example,

sequence <- 1:2
for (i in sequence) {
  print(i)
  sequence <- 0
}

will print the numbers 1 and 2, and then will finish, with sequence containing a single zero.

This is described in the help page ?"for":

The seq in a for loop is evaluated at the start of the loop; changing it subsequently does not affect the loop. If seq has length zero the body of the loop is skipped. Otherwise the variable var is assigned in turn the value of each element of seq. You can assign to var within the body of the loop, but this will not affect the next iteration. When the loop terminates, var remains as a variable containing its latest value.

CodePudding user response:

No, for loops in R can be considered a function call that iterates over the inputs "by value" (eg. by copying the input). Any change to the iterator sequence after start will leave the for-loop iteration unaffected. This is in general good practice as it drastically reduces bad coding practice and infinite loops. This is easily illustrated with a simple example:

idx <- 1:15
for(i in idx){
  idx <- head(idx, -1)
  cat('idx: ', idx, '\n')
  cat('i: ', i, '\n')
}

If you want to update the iterator your best bet is either repeat or while but be careful as it increases the potential for errors and unexpected infinite loops.

idx <- 1:15
while(length(idx) != 0){
  i <- head(idx, 1)
  idx <- tail(idx, -1)
  cat('idx: ', idx, '\n')
  cat('i: ', i, '\n')
}
  •  Tags:  
  • Related