Increment counter in for loop in R

Hi everyone, I have a problem with the counter that I created in the for loop. Here is the code.

n1<- 0 n2<- 0 n<- 20 f<- rep(NA,20) set.seed(10) x<- runif(20) for(i in 1:20) { f[i]<- ifelse(x[i]<0.5, 'a', 'b') if((n1-n2)==2) { break } if(f[i]=='a') n1<- n1 + 1 else n2<- n2 + 1 # n1 counts a 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 

As you can see from the result number a = 5 and b's = 2. But when I call n1 and n2, it returns 4 for n1, which is wrong. Why is this? How am I wrong? Thanks in advance.

I start sampling a and b with a probability of 0.5.20. At some point that I don’t know about in advance, the number a - the number b is greater than 2. When this happens, I want the sampling probability to change to 0.2. What I'm trying to achieve.

+8
for-loop r counter
source share
1 answer

ifelse vectorized, so there is no need to use for-loop . This is how you should use it:

 set.seed(10) x <- runif(20) f <- ifelse(x<0.5, 'a', 'b') 

Then use table to count the occurrence:

 table(f) f ab 13 7 

To get n1 :

 n1 <- table(f)[['a']] 

EDIT OP wants to change the pattern according to appearance a and b. You should use if and else not ifelse . You must also first allocate memory for the vector f.

 n1 <- 0 ; n2 <- 0 N <- 20 f <- vector(mode='character',N) set.seed(10) x<- runif(N) for(i in seq(N)) { if (x[i] <0.5){ f[i] <- 'a' n1 <- n1 +1 } else { f[i] <- 'b' n2 <- n2 +1 } if((n1-n2)==2) x <- runif(N) ## condition to regenerate sample } 
+8
source share

All Articles