Day 11 of 30·Functions & Macro-like Behavior
User-Defined Functions: Replacing the SAS Macro
Why an R function is clearer, safer and easier to test than a %MACRO.
Learning objectives
- 1Write functions with named, default arguments.
- 2Understand return values and local scope.
- 3Contrast text-substitution macros with true functions.
- 4Build a small reusable derivation function.
Key SAS® → R comparison
| Task | SAS® | R |
|---|---|---|
| Define routine | %macro f(x); ... %mend; | f <- function(x) { ... } |
| Call it | %f(age) | f(age) |
| Default arg | %macro f(x, d=0); | function(x, d = 0) |
| Return value | (via &-variable / dataset) | explicit return() or last value |
Code examples
SAS®
%macro bmi(wt, ht);
&wt / ((&ht/100)**2)
%mend;R
bmi <- function(wt, ht) {
wt / (ht/100)^2
}
bmi(72, 178) # 22.7Note: An R function takes typed values and returns a value — no text substitution, no global side effects.
Explanation
A SAS macro substitutes text before the code runs; an R function operates on actual values at run time. That difference makes R functions easier to reason about, unit-test, and reuse, because arguments have real scope and the function returns a concrete object.
Default arguments, named arguments, and a clear return value let you encapsulate derivations once and apply them consistently across datasets — the building block for everything in this phase.
Practice exercise
Write a function that takes weight and height and returns BMI rounded to one decimal, with a default height unit, and apply it across a VS dataset with mutate().