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)
agstudy
source share