5 Control flow
Q: What type of vector does each of the following calls to
Read the documentation and write down the rules in your own words.
A: The arguments of
ifelse()operates elementwise, so when
noare shorter than
test, they will be recycled. (When they are longer than
test, their additional elements will be ignored.)
The function returns the entry for
NA). The final object is coerced according to usual coercion rules with attributes (including the class) being stripped. Therefore, the expressions above return vectors of type
Q: Why does the following code work?
if()expects a logical condition. Objects of other types are coerced to logical if possible.
0is coerced to
FALSEwhile other numeric input is coerced to
TRUE. Numeric input which is not logically interpretable by
NA_real, will lead to an error.
Q: Why does this code succeed without errors or warnings?
A: The vector we are iterating over are of length 0. Our loop goes from
i = 1to
i = 0. As we use
[for indexing, we need to be aware of their subsetting behaviour for out-of-bounds and zero indices.
During the first iteration
xwill generate an
NA(out-of-bounds indexing for atomics). The resulting
NA(from squaring) will be assigned to the empty length-1 list
out(out-of-bounds indexing for lists).
In the next iteration,
numeric(0)(zero indexing for atomics). Again squaring doesn’t change the value and
numeric(0)is assigned to
out(zero indexing for lists). Please be aware, that
outdoesn’t change during the last iteration.
Overall the code works, because each step includes valid R operations. (Though it may have been very helpful to warn the user about the unusual inputs to this loop.)
Q: What does the following code tell you about when the vector being iterated over is evaluated?
A: In this loop
xtakes on the values of the initial
3), which evaluated just once in the beginning of the loop.
Q: What does the following code tell you about when the index is updated?
A: In a
for-loop the index is updated in the beginning of each iteration. Therefore, reassigning the index symbol during one iteration doesn’t affect the following iterations.