Quiz
You have finished the iteration section: why vectorization beats loops, the apply family, the purrr map functions and their typed variants, iterating over several inputs, and resilient iteration with safely. This short quiz checks what stuck. Pick an answer to continue; you can retry until it clicks. The last two steps are live R, run them and tinker.
What vectorization means
Why is prices * 1.1 preferred over a for loop that multiplies each price one at a time?
lapply versus sapply
What is the difference between lapply() and sapply()?
lapply when you want a list for sure, sapply when a tidy vector would be nicer.A typed map
You want a numeric vector out of a map, guaranteed, not a list. Which purrr function fits?
map_dbl() guarantee the output type, which catches surprises early.map2() is for iterating over two inputs, not for fixing the output type.Iterating over two inputs
You have a vector of prices and a matching vector of quantities, and you want price times quantity per item. Which tool is built for this?
map2(prices, qtys, ~ .x * .y) pairs the first with the first, the second with the second, and so on.sum() collapses to one number; you want one result per item.Surviving a bad element
You map a function over a list, and one element makes it error. You want the whole run to finish, capturing the failure instead of stopping. Which helper fits?
safely() turns a risky function into one that always returns, so a single bad element cannot sink the run.safely() and possibly() are made exactly for this.When a loop is fine
Which statement is the most honest?
sapply in live R
Square each number from 1 to 6, getting a clean vector back. Run it, then change the function to function(x) x * 10.
sapply() applies your function to each element and simplifies the results into a single vector, no loop bookkeeping required.
map_dbl in live R
Do the same square with purrr, but demand a numeric vector out. Run it, then try map_chr and read the error it raises about the wrong type.
map_dbl() returns a double vector and would stop if any result were not a number, which is how the typed variants protect you from silent surprises.
Section complete
Strong work. You can say why vectorization beats a loop, tell lapply from sapply, pick a typed map_dbl when you need a vector, reach for map2 over two inputs, use safely to survive a bad element, and judge when a plain loop is still fine. Next section: defensive code and debugging.