Hello everyone i have a problem with a counter i have created in a 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'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
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 .
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.
ifelse
is vectorized so no need to use a for-loop
here. This how you should use it:
set.seed(10)
x <- runif(20)
f <- ifelse(x<0.5, 'a', 'b')
Then Use table
to count occurrence:
table(f)
f
a b
13 7
To get n1
:
n1 <- table(f)[['a']]
EDIT OP wants to change the sample according to the occurrence of a and b. You should use if
and else
not ifelse
. You should also preallocate memory for 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With