CephBirk - 1 month ago 6x

R Question

What is the best way to have a

`while`

Here's my situation:

`diff_val = Inf`

last_val = 0

while(diff_val > 0.1){

### calculate val from data subset that is greater than the previous iteration's val

val = foo(subset(data, col1 > last_val))

diff_val = abs(val - last_val) ### how much did this change val?

last_val = val ### set last_val for the next iteration

}

The goal is to have

`val`

`val`

`val`

`while`

`val`

`while`

I know of

`break`

`while(diff_val > 0.1){`

val = foo(subset(data, col1 > last_val))

diff_val = abs(val - last_val)

last_val = val

if(val == val_2_iterations_ago) break

}

How can I create

`val_2_iterations_ago`

Apologies for the non-reproducible code. The real

`foo()`

`data`

Answer

I don't know if just keeping track of the previous two iterations will actually suffice, but it isn't too much trouble to add logic for this.

The logic is that at each iteration, the second to last value becomes the last value, the last value becomes the current value, and the current value is derived from `foo()`

. Consider this code:

```
while (diff_val > 0.1) {
val <- foo(subset(data, col1 > last_val))
if (val == val_2_iterations_ago) break
diff_val = abs(val - last_val)
val_2_iterations_ago <- last_val
last_val <- val
}
```

Source (Stackoverflow)

Comments