Home > front end >  How runloop by flag condition in R?
How runloop by flag condition in R?

Time:10-24

Suppose there is loop

x <- c(2,5,3,9,8,11,6)
count <- 0
for (val in x) {
if(val %% 2 == 0)  count = count 1
}

and there is flag variable. How to do that if flag=TRUE then run this loop and if flag has any other value then ignore run loop.Just continue to execute the rest of the code.

CodePudding user response:

Several alternatives:

  1. Don't loop if !flag:

    flag <- FALSE
    x <- c(2,5,3,9,8,11,6)
    count <- 0
    if (flag) {
      for (val in x) {
        if(val %% 2 == 0)  count = count 1
      }
    }
    count
    # [1] 0
    
  2. break out of the loop early:

    flag <- FALSE
    x <- c(2,5,3,9,8,11,6)
    count <- 0
    for (val in x) {
      if (!flag) break
      if(val %% 2 == 0)  count = count 1
    }
    count
    # [1] 0
    
  3. while loop, self-incrementing the loop, and break out if !flag. I'm not going to code this, since it adds no benefit to #1 yet adds the risk that unconstrained (if poorly-written) while loops can introduce.

  4. Avoid the loop, do this directly:

    flag <- FLASE
    sum(flag & x %% 2 == 0)
    # [1] 0
    
    flag <- TRUE
    sum(flag & x %% 2 == 0)
    # [1] 3
    
  •  Tags:  
  • r
  • Related