user3058633
user3058633

Reputation: 91

How to write a loop that runs until a condition is satisfied

I have written the following loop in R. I want the loop to keep running until there is a case where Y is greater than or equal to 3. I then want to display T which is the number of experiments run until this outcome occurs for the first time.

T=0
while(Y<3)
{
  X=rbinom(1,5,0.5)
  Y=rbinom(1,X,0.5)
  Outcome=Y
  T=T+1
}
T 

I am very new to R and I'm unsure how to change what i've done to achieve what I need.

Upvotes: 0

Views: 5335

Answers (4)

Sheikh
Sheikh

Reputation: 57

If you don't know how many times you are to perform the loop, while loop is used in that case. It performs the looping until your desired condition is satisfied. You can try the following codes.

T=0 #Index variable
Y=2 #Initial value that starts the while looping

At first while loop inspect this initial Y=2, if it satisfies the condition then the lopping starts until the condition gets dissatisfied.

while(Y<3) #Initialization of your looping
{
  X=rbinom(1,5,0.5)
  Y=rbinom(1,X,0.5)
  T=T+1
}
T 

Upvotes: 1

Roland
Roland

Reputation: 132969

You don't need a loop for this. The following uses R's vectorization and is much more efficient.

set.seed(42) #for reproducibility
n <- 1e4 #increase n and rerun if condition is never satisfied
X=rbinom(n,5,0.5) 
Y=rbinom(n,X,0.5)

#has condition been satisfied?
any(Y>3)
#TRUE

#first value that satisfies the condition
which.max(Y>3)
#[1] 141

Upvotes: 2

Christopher Louden
Christopher Louden

Reputation: 7592

You can use a do until construction:

while(TRUE){
  # Do things
  if(Y >= 3) break()
}

Upvotes: 2

alko989
alko989

Reputation: 7938

The first time the while checks its condition it does not find Y. Try to initialize Y to something less than 3.

Y <- 0

Upvotes: 0

Related Questions