26.3 For loop variations

There are four variations on the basic theme of the for loop:

  1. Modifying an existing object, instead of creating a new object.

  2. 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-effects

      • for (nm in names(xs)) - creates name to access value with x[[nm]]

  3. 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.

  4. Handling sequences of unknown length.

    • Use a while loop.