Adding a counter to a loop

28,280

Solution 1

You basically had it. You just need to a) initialize the counter before the loop, b) use & instead of and in your if condition, c) actually add 1 to the counter. Since adding 0 is the same as doing nothing, you don't have to worry about the "else".

counter = 0
for (blah in your_loop_definition) {
    ... loop code ...
    if(hours$week1 > 1 & hours$week1 < 48) {
        counter = counter + 1
    }
    ... more loop code ...
}

Solution 2

Instead of

if(hours$week1 > 1 & hours$week1 < 48) {
    counter = counter + 1
}

you could also use

counter = counter + (hours$week1 > 1 && hours$week1 < 48)

since R is converting TRUE to 1 and FALSE to 0.

Share:
28,280
Sergio Henriques
Author by

Sergio Henriques

Updated on July 09, 2022

Comments

  • Sergio Henriques
    Sergio Henriques almost 2 years

    On a broad question that I haven't been able to find for R:

    I'm trying to add a counter at the beginning of a loop. So that when I run the loop sim = 1000:

    if(hours$week1 > 1 and hours$week1 < 48) add 1 to the counter 
    ifelse add 0
    

    I have came across counter tutorials that print a sentence to let you know where you are (if something goes wrong): e.g

    For (i in 1:1000) {
        if (i%%100==0) print(paste("No work", i)) 
    }
    

    But the purpose of my counter is to generate a value output, measuring how many of the 1000 runs in the loop fall inside a specified range.