4

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.

alistaire
  • 42,459
  • 4
  • 77
  • 117
Sergio Henriques
  • 135
  • 1
  • 1
  • 6
  • 2
    Try to give a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) along with the expected output. – Ronak Shah Dec 08 '17 at 02:03
  • 2
    What is the problem with using your second suggested loop, and just maintaining a counter declared outside the loop? – Tim Biegeleisen Dec 08 '17 at 02:04

4 Answers4

3

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 ...
}
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

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.

sigbert
  • 77
  • 5
0

How about this?


count = 0

for (i in 1:1000) {

  count = ifelse(i %in% 1:100, count + 1, count)

}

count

#> [1] 100
ardaar
  • 1,164
  • 9
  • 19
0

If your goal is just to monitor progression coarsely, and you're using Rstudio, a simple solution is to just refresh the environment tab to check the current value of i.

ostermann
  • 101
  • 4