Home > Back-end >  For loop inside which it's possible to modify the index
For loop inside which it's possible to modify the index

Time:10-05

I'd like to know how can I implement a for loop like this in R (I wrote the code for C):

int i;
for (i = 1; i<=10; i  ) {
    print the index i
    i = desiredNumber
}

It seems that this is not possible in R because, when I modify the index inside a for loop, nothing happens.

CodePudding user response:

We can use a while loop

flag <- TRUE
 i <- 1
 while(flag) {
   print(i)
   i <- i   1
   if(i > 10) {
    flag <- FALSE
   }
 
 
 }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
  • Related