Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I just want to try to break a loop by having a condition that checks whether the last value of each of three vectors satisfies a particular condition that that may have taken place at that iteration OR past iterations of the loop.

Below is a very simple version of what I am trying to do.

Consider the following loop:

period = c(1:100)

x1 = 6

x2 = 8

x3 = 10

x = c()

for(t in 1:length(period)){x[t] = sample(c(x1,x2,x3), size = 1, replace = TRUE, prob = c(0.6,0.35,0.05))}

I am just wondering how I can make it such that this loop stops once each value has been sampled at least once. That is, the loop stops when each of x1,x2,x3 have been sampled.

1 Answer

0 votes
by (108k points)

What you can do is you can use while loop and continue it until all the 3 values are not present in x.

x1 <- 6

x2 <- 8

x3 <- 10

i <- 1

x = c()

flag <- TRUE

while(flag){

  x[i] <- sample(c(x1,x2,x3), size = 1, prob = c(0.6,0.35,0.05))

  i <- i + 1

  if (all(c(x1, x2, x3) %in% x)) flag <- FALSE

}

x

#[1]  6  6  6  6  6  8  6  6  8  8  8  6  6  8  8  8  6  6  6  8 10

But there will be a variation without using flag :

while(TRUE){

  x[i] <- sample(c(x1,x2,x3), size = 1, prob = c(0.6,0.35,0.05))

  i <- i + 1

  if (all(c(x1, x2, x3) %in% x)) break

}

 If you are a beginner and want to know more about R then do refer to the following R programming tutorial.

Browse Categories

...