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
apply family of functions over traditional loops in R?lapply on a list named my_list applying the function sqrt?lapply(X, FUN) where X is the list and FUN is the function to apply.mat <- matrix(1:6, nrow=2) result <- apply(mat, 2, sum) print(result)
apply with margin 2 applies the function to columns.vec <- 1:5 result <- sapply(vec, function(x) x^2) print(result)
my_list <- list(a = 1:3, b = 4:6, c = 7:9). You want to create a named vector with the mean of each element but only include those means greater than 5. Which R code correctly does this using apply family functions?Pass the test and this pattern moves unknown