SAS (Base SAS)+
*==============================================================================;
* Create sample ADSL data;
*==============================================================================;
data adsl;
input usubjid $ trt01p $ age sex $;
datalines;
SUBJ001 Placebo 67 M
SUBJ002 DrugA 59 F
SUBJ003 Placebo 72 F
SUBJ004 DrugA 65 M
SUBJ005 Placebo 60 F
SUBJ006 DrugA 55 M
SUBJ007 Placebo 70 M
SUBJ008 DrugA 63 F
;
run;
*==============================================================================;
* Define a macro with keyword parameters and defaults;
*==============================================================================;
%macro trt_summary(ds=adsl, var=age, trt=);
*--- Subset to the requested treatment arm ---;
data _subset;
set &ds.;
where trt01p = "&trt.";
run;
*--- Calculate summary statistics ---;
proc means data=_subset n mean std min max;
var &var.;
title "Summary of %upcase(&var.) for &trt.";
run;
%mend trt_summary;
*==============================================================================;
* Call the macro for each treatment group;
*==============================================================================;
%trt_summary(trt=Placebo);
%trt_summary(trt=DrugA);
%trt_summary(ds=adsl, var=age, trt=Placebo);- To define a reusable block in SAS, we wrap our logic in
%MACRO name(params) ... %MEND;. - Keyword parameters are declared with
name=defaultsyntax β hereds=adslandvar=agehave defaults, whiletrt=is required (no default). - Inside the macro, we reference each parameter with the
&name.syntax, just like any macro variable. - The trailing dot on
&ds.,&var., and&trt.tells SAS where the variable name ends β essential when the next character could be mistaken as part of the name. - We use
%upcase(&var.)in the TITLE statement to display the variable name in uppercase β showing that macro functions work inside macro code. - To call the macro, we write
%trt_summary(trt=Placebo);β parameters we omit pick up their defaults. - The third call spells out every parameter explicitly, which is good practice for readability in production code.
- After running, we confirm two PROC MEANS outputs: one for the Placebo arm, one for DrugA, each showing N, mean, std, min, and max of AGE.