Changing the loop index in a loop

I'm relatively new to R. I'm iterating over a vector in R using the 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 index of the cycle in the cycle. I tried this, but somehow did not change it. There must be some achievement in R.

Thanks in advance. Themselves

+7
source share
4 answers

You can change the loop index in a for loop, but this will not affect the execution of the loop; see "Details" ?"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 and index it manually:

 i <- 1 while(i < 100) { # do stuff if(condition) { i <- i+3 } else { i <- i+1 } } 
+9
source

Take a look

 ?"next" 

The next command will skip the rest of the current iteration of the loop and start the next. This can accomplish what you want.

+8
source

Without an example, it's hard to understand what you want to do, but you can always use an if-statement inside a for loop:

 foo <- 1:10*5 for (i in seq(length(foo))) { if (foo[i] != 15) print(foo[i]) } 
+2
source

In R, local changes in the index variable are β€œfixed” with the following pass:

  for (i in 1:10){ if ( i==5 ) {i<-10000; print(i)} else{print(i)} } #----- [1] 1 [1] 2 [1] 3 [1] 4 [1] 10000 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10 

Since you have some criterion for omissions, you should apply the criterion to the loop vector inside the brackets. For example:

  for( i in (1:10)[-c(3,4,6,8,9)] ) { print(i)} #---- [1] 1 [1] 2 [1] 5 [1] 7 [1] 10 
+2
source

All Articles