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.

2
  • 2
    Try to give a reproducible example along with the expected output. Commented Dec 8, 2017 at 2:03
  • 2
    What is the problem with using your second suggested loop, and just maintaining a counter declared outside the loop? Commented Dec 8, 2017 at 2:04

4 Answers 4

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 ...
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

How about this?


count = 0

for (i in 1:1000) {

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

}

count

#> [1] 100

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.