title: Increase counter in a for loop in R
body: <p>Hello everyone i have a problem with a counter i have created in a for loop. Here is the code.</p>
  
  <pre><code>n1&lt;- 0
  n2&lt;- 0
  n&lt;- 20
  f&lt;- rep(NA,20)
  set.seed(10) 
  x&lt;- runif(20)
  for(i in 1:20) {
  f[i]&lt;- ifelse(x[i]&lt;0.5, 'a', 'b')
  if((n1-n2)==2) {
  break
   }
   if(f[i]=='a')  
  n1&lt;- n1 + 1 else n2&lt;- n2 + 1 # n1 counts a's n2 counts b's
  }
  
  [1] "b" "a" "a" "b" "a" "a" "a" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA
  </code></pre>
  
  <p>As you can see from the result number of a's=5 and b's=2 . But when i call n1 and n2 it returns 4 for n1 which is wrong . Why is that? How am I wrong ? Thanks in advance .</p>
  
  <p>I start sampling a's and b's with probability 0.5 .20 total. At some point which i dont know in advance, the number of a's - the number of b's exceeds 2. When this happens i want the sampling probability to change to 0.2  Thats what i am trying to achieve. </p>