Day 13 of 30·Functions & Macro-like Behavior
Functional Iteration with purrr::map()
Apply a function across many elements or datasets without writing loops.
Learning objectives
- 1Use map(), map_dfr(), map2() and walk().
- 2Replace repetitive macro %DO loops with map().
- 3Return type-stable output with map_chr/dbl/int.
- 4Iterate a derivation across a list of datasets.
Key SAS® → R comparison
| Task | SAS® | R |
|---|---|---|
| Loop a macro | %do i=1 %to 5; | map(1:5, ~ ...) |
| Stack results | append datasets in loop | map_dfr(files, read_csv) |
| Two inputs | parallel macro vars | map2(x, y, ~ ...) |
| Side effects | loop with put/output | walk(x, ~ ...) |
Code examples
SAS®
/* macro loop over a filename list,
PROC IMPORT each, PROC APPEND */R
library(purrr); library(readr)
files <- list.files("raw", "\\.csv$", full.names = TRUE)
all <- map_dfr(files, read_csv, .id = "source")Note: map_dfr applies read_csv to each path and row-binds the results into one tibble in a single line.
Explanation
purrr brings functional iteration: map() applies a function to each element of a list or vector and returns a list, while the typed variants (map_dfr, map_chr, map_dbl) guarantee the shape of the output. This replaces the macro %DO loop pattern with a single, declarative call.
Iterating a derivation across a list of by-group datasets, reading a directory of files, or fitting a model per subject all become one-liners — and because the output type is fixed, mistakes surface immediately instead of silently.
Practice exercise
Use map_dfr() to import every .csv in a folder into one stacked tibble with a source identifier, then use map() to apply a summary function to a list of split-by-arm datasets.