CIVL6001 Chap.8 Conditions, Loops and Reproducible Checks
Conditions, Loops and Reproducible Checks
Conditions translate engineering rules into explicit logical tests, while loops repeat a visible operation across a sequence. Reliable control flow begins with an initial state, handles missing values, updates one result and verifies termination. R may recycle unequal vectors or complete an incorrect loop without stopping, so successful execution must be paired with independent checks and deliberate failure cases.
An if statement should express mutually exclusive branches, including exact boundary values and missing inputs. The order of tests matters because a broad condition can capture values intended for a later branch. A loop needs an initial state, a sequence or stopping rule, an update and a result whose meaning remains stable after every iteration.
Counters should be initialised outside the loop, and while loops require both a tolerance and a maximum iteration guard so failure to converge cannot continue indefinitely. Climate datasets add alignment hazards. R can recycle a shorter vector during arithmetic, producing output with only a warning, while trimming records to equal length can silently pair the wrong timestamps.
Explicit length checks and joins on stable keys protect the physical correspondence of measurements. Verification should use a second method with different failure modes, such as comparing a loop count with a vectorised logical sum. Agreement increases confidence but does not prove semantic correctness, because both methods can share the wrong units or threshold.
Deliberate failure cases make protections observable: insert a missing value, duplicated timestamp, negative measurement or unequal vector and confirm that the script stops or reports the intended branch. Code is complete only when normal cases, boundaries and expected failures have been exercised. This approach turns control flow into a transparent statement of the engineering rule and its limits.
What this chapter covers
- 01
if and else branches
- 02
logical boundaries
- 03
loop initialisation
- 04
counters and accumulators
- 05
vector length safety
- 06
negative controls and assertions
Worked example · free
Count heat threshold exceedances
- 1Initialise count at zero.
- 1Loop across each value.
- 1Handle missingness explicitly.
- 1Return a count of two.
- 1Verify with a vectorised sum.
Key terms
- Conditional branch
- A code path selected by the truth value of an explicit logical test.
- Accumulator
- An object updated across loop iterations to store a running result.
- Negative control
- A deliberate failure case used to prove that a validation check is active.
Conditions, Loops and Reproducible Checks FAQ
When is a loop useful in R?
A loop is useful when repeated state changes or bespoke checks need to remain visible. Vectorised code may be shorter, but a clear loop can be easier to audit for cumulative calculations and teaching examples.
Why is vector recycling risky?
R can repeat a shorter vector during arithmetic and still return numbers. Climate records should normally be aligned by explicit timestamps and keys. Recycling does not prove that rows refer to the same observations.
What proves that code is correct?
No single successful run proves correctness. Use small known cases, independent calculations, assertions, expected failures, length checks and range checks. Verification should test both the numerical result and the engineering meaning of the operation.
Exam move
Write every control flow exercise as a contract before coding: initial state, input sequence, condition, update, termination and independent check. Begin with a sign classifier and make the positive, zero, negative and missing branches mutually exclusive. Test the exact boundary values rather than only obvious examples. Then recreate the threshold counter with the five element temperature vector.
Initialise the counter outside the loop, handle missingness before comparison and retain the indices of exceedances as well as the total. Verify the answer with a vectorised logical sum. Explain why agreement is useful and why it still does not prove correctness for every future input. Create an unequal length vector example and observe R recycling the shorter vector. Replace that behaviour with an explicit length check.
For real time series, align records by timestamp or another stable key rather than trimming both vectors to the same size, because a missing row in the middle can shift every later pair. Revisit the Week 2 π approximation as an iteration problem. Write the tolerance, maximum iteration count and known reference before starting. Inspect whether the sequence converges, oscillates or stops for the wrong reason.
A small numerical change is not proof that the formula or units are correct. Add one deliberate failure to each script: an NA, a negative sensor value, a duplicated key or a vector of the wrong length. Confirm that the assertion or branch produces the expected message. These negative controls show that protection is active. For oral revision, explain a loop without reading code.
State what remains true after each iteration, what the counter represents and how termination is guaranteed. Finish by comparing the loop result with an independent method and by printing enough detail to investigate discrepancies. The recurring lesson is that code which returns a number has completed execution; an engineering result is accepted only after its boundaries, units and verification checks also pass.