0

I have a code as follows:

#1
evolve = function(N,p0,s){
tot.fit = p0*(1+s)+(1-p0)
A.fit= p0*(1+s)
return(rbinom(1,N,(A.fit/tot.fit))/N)
}

#2

N <- 1000
p <- 0.02
pvector = c() 

while(p<1 & (1-p)<1){

px <- evolve(N,p,0.02)
Nm <- 20
p <- (N*px)/(N+Nm)
pvector <- c(pvector, px)
}

The end value of tail(pvector, n=1) can only reach either 0 or 1. I want to modify my script in a way that the part 2 of my script runs in a loop, as many times as it takes to get the final tail(pvector, n=1) value to be 1, at least 20 times. When it reaches the end iteration of the 20th time tail(pvector, n=1) being 1, I would also want to know how many times till then was it 0.

How do I do it?

rishi
  • 267
  • 1
  • 9
  • Possible duplicate of [do-while loop in R](https://stackoverflow.com/questions/4357827/do-while-loop-in-r) – Aramis7d May 30 '18 at 13:16

1 Answers1

0

You can use repeat loop in r as follows:

count1s <- 0
count0s <- 0
repeat 
{ 
  #code to be repeated
 count1s <- count1s + 1;
 if(tail(pvector, n=1) == 0)
    count0s <- count0s + 1
 if(tail(pvector, n=1) == 1 & count1s >=20)
   break;
}

count0s will give you the number of times tail(pvector, n=1) has 0 and count1s will help you in repeating the loop atleast 20 times with tail(pvector, n=1) having value 1.

krpa
  • 84
  • 1
  • 13