26.3 For loop variations
There are four variations on the basic theme of the for
loop:
Modifying an existing object, instead of creating a new object.
Looping over names or values, instead of indices.
There are three basic ways to loop over a vector.
for (i in seq_along(df))
for (x in xs)
- good for side-effectsfor (nm in names(xs))
- creates name to access value withx[[nm]]
Handling outputs of unknown length.
unlist()
flattens a list of vectors into a single vector,purrr::flatten_dbl()
is stricter — it will throw an error if the input isn’t a list of doubles.
Handling sequences of unknown length.
- Use a
while
loop.
- Use a