Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a counter to a loop

Tags:

loops

for-loop

r

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.

like image 233
Sergio Henriques Avatar asked Sep 17 '25 05:09

Sergio Henriques


1 Answers

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 ...
}
like image 171
Gregor Thomas Avatar answered Sep 19 '25 18:09

Gregor Thomas