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
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.
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.
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.
Yes, it is, there is no restriction about it. In C++ is also very common creating for loops with iterators.
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With