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:
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
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
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.Avoid the loop, do this directly:
flag <- FLASE sum(flag & x %% 2 == 0) # [1] 0 flag <- TRUE sum(flag & x %% 2 == 0) # [1] 3