Concept Flow - Apply family vs loops
Start with data
Choose method
Use loop
Iterate over
each element
Collect results
Output
This flow shows how you start with data, choose between loops or apply functions, process each element, and collect results.
x <- 1:3 # Using loop res_loop <- rep(NA, length(x)) for(i in seq_along(x)) { res_loop[i] <- x[i]^2 } # Using sapply res_apply <- sapply(x, function(n) n^2)
| Step | i (index) | x[i] | Loop Action | res_loop | sapply Action | res_apply |
|---|---|---|---|---|---|---|
| 1 | 1 | 1 | Calculate 1^2=1 | 1 NA NA | Calculate 1^2=1 | 1 4 9 |
| 2 | 2 | 2 | Calculate 2^2=4 | 1 4 NA | Already calculated | 1 4 9 |
| 3 | 3 | 3 | Calculate 3^2=9 | 1 4 9 | Already calculated | 1 4 9 |
| End | - | - | Loop ends after i=3 | 1 4 9 | sapply finished all | 1 4 9 |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | - | 1 | 2 | 3 | - |
| res_loop | NA NA NA | 1 NA NA | 1 4 NA | 1 4 9 | 1 4 9 |
| res_apply | - | - | - | - | 1 4 9 |
Apply family vs loops in R: - Loops: explicit iteration, step-by-step assignment - Apply functions: concise, internal iteration - Initialize vectors before loops for speed - Apply returns full result at once - Use apply for cleaner, often faster code