Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing loop index within loop

I am relatively new to R. I am iterating over a vector in R by using for() loop. However, based on a certain condition, I need to skip some values in the vector. The first thought that comes to mind is to change the loop index within the loop. I have tried that but somehow its not changing it. There must be some what to achieve this in R.

Thanks in advance. Sami

like image 240
Sami Avatar asked May 06 '11 14:05

Sami


People also ask

Can you change i inside a for loop?

A for loop assigns a variable (in this case i ) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i will become the next element. The while loop has no such restriction.

What is loop index in for loop?

An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.

How do I loop a second index in Python?

If you want to iterate through a list from a second item, just use range(1, nI) (if nI is the length of the list or so). i. e. Please, remember: python uses zero indexing, i.e. first element has an index 0, the second - 1 etc. By default, range starts from 0 and stops at the value of the passed parameter minus one.

Can we use a double value as in index in a for loop?

Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators.


2 Answers

You can change the loop index within a for loop, but it will not affect the execution of the loop; see the Details section of ?"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.

Use a while loop instead and index it manually:

i <- 1
while(i < 100) {
  # do stuff
  if(condition) {
    i <- i+3
  } else {
    i <- i+1
  }
}
like image 54
Joshua Ulrich Avatar answered Sep 30 '22 05:09

Joshua Ulrich


Look at

?"next"

The next command will skip the rest of the current iteration of the loop and begin the next one. That may accomplish what you want.

like image 37
Greg Snow Avatar answered Sep 30 '22 07:09

Greg Snow