ausworli
ausworli

Reputation: 519

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):

while((theta_diff[1]>epsilon)|(theta_diff[2]>epsilon))
{
  }

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.

while(all(theta_diff>epsilon))
{
  }

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.

Upvotes: 1

Views: 1838

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73325

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 ....

Upvotes: 1

Related Questions