Shambhavi Srivastava Shambhavi Srivastava - 1 year ago 80
R Question

R : Run while loop until all elements of a vector are less than a threshold

In R, I want my while loop to continue until each element in a particular vector 'theta_diff' (which is updated in the while loop in each iteration) reduces below a particular threshold 'epsilon'.
Presently I am able to achieve this by using an OR condition in the while loop test condition (theta_diff is a 2-element vector):


I am wondering if there is a smarter way to do this? I tried the all() but it implements a AND logic instead of an OR logic and so even if one of the theta_diff elements meet the criteria, the while loop stops.


Main inspiration to search for a smarter option is that: depending upon the program, the dimension of the theta_diff vector may change and I want to make the while loop condition independent of the length of the theta_diff vector.

Answer Source

I could come up with two options (at least one element of theta_diff is greater than epsilon):

  • any(theta_diff > epsilon)
  • max(theta_diff) > epsilon

Similarly, the following two are equivalent (all elements of theta_diff are greater than epsilon):

  • all(theta_diff > epsilon)
  • min(theta_diff) > epsilon

Sometimes using repeat is more readable than using while. Why not consider:

repeat {
  ## blablabla
  if (all(theta_diff > epsilon)) break

which means do ... until ....

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download