# Stopping a Loop When a Condition is Met

I created the following loop that generates 1000 random numbers - and then repeats this process 10 times:

``````results <- list()

for (i in 1:10){

a = rnorm(1000,10,1)
b = rnorm(1000,10,1)

d_i = data.frame(a,b)
d_i\$index = 1:nrow(d_i)
d_i\$iteration = as.factor(i)

results[[i]] <- d_i

}

results_df <- do.call(rbind.data.frame, results)
``````

Question: I would like to change this loop such that instead of only generating 1000 random numbers, it keeps generating random numbers until a certain condition is met, for example: KEEP generating random numbers UNTIL d_i\$a > 10 AND d_i\$b > 10.

Using a "WHILE()" statement, I tried to do this:

``````results <- list()

for (i in 1:10){

while (d_i\$a > 10 & d_i\$b >10) {

a = rnorm(1000,10,1)
b = rnorm(1000,10,1)

d_i = data.frame(a,b)
d_i\$index = 1:nrow(d_i)
d_i\$iteration = as.factor(i)

results[[i]] <- d_i

}

}

results_df <- do.call(rbind.data.frame, results)
``````

Problem: However, this returns the following warnings (10 times):

``````Warning messages:
1: In while (d_i\$a > 10 & d_i\$b > 10) { :
the condition has length > 1 and only the first element will be used
``````

And produces an empty table:

``````> results_df

data frame with 0 columns and 0 rows
``````

Thanks!

The code, as supplied, does not run since "d_i" is not defined at the start of the "while" loop. You could define it at the start of the loop, but perhaps a better way is to set a flag to FALSE and define a condition like "flag <- ..." at the end of the loop to determine when the while loop has to be exited.

The other problem is the warning about "the condition has length > 1 and only the first element will be used". That warning is because you have not defined the condition correctly. You would need to do something like: "(all(d_i\$a > 10) & all(d_i\$b >10))" or something similar. But, again, I'm not sure about your criterion for exiting the loop and what you're trying to achieve.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.