Does R allow to define variables within a while-statement? I have a while loop that should continue as long as one of two conditions is true. However, I also need the result of both conditions within the while loop. The functions that compute the conditions are computationally expensive and thus simply re-computing them is not an option.
while (a = conditionA() || b = conditionB())
{
do_some_work(a)
some_more_work(a, b)
}
My current work around is the following.
a = conditionA()
b = conditionB()
while (a || b)
{
do_some_work(a)
some_more_work(a, b)
a = conditionA()
b = conditionB()
}
However, you all understand that this solution just feels wrong. Among others, it pollutes the scope outside the while loop and it is just not preferred to add the unnecessary lines of code.
Alternatively, we can use repeat
as explained in the post referred to in the comment. Although this avoids polluting the scope outside the loop, IMO it is less readable than defining variables within the while statement.
repeat
{
a = conditionA()
b = conditionB()
if (!a && !b)
break
do_some_work(a)
some_more_work(a, b)
}