SAS (Base SAS)+
*==============================================================================;
* Create sample ADLB data;
*==============================================================================;
data adlb;
input usubjid $ paramcd $ aval;
datalines;
SUBJ001 ALT 25
SUBJ001 AST 30
SUBJ001 BILI 0.8
SUBJ002 ALT 40
SUBJ002 AST 35
SUBJ002 BILI 1.2
SUBJ003 ALT 22
SUBJ003 AST 28
SUBJ003 BILI 0.6
SUBJ004 ALT 38
SUBJ004 AST 42
SUBJ004 BILI 1.5
;
run;
*==============================================================================;
* Pattern 1: %DO loop with a counter;
*==============================================================================;
%macro loop_counter(n=3);
%do i = 1 %to &n.;
%put Iteration &i. of &n.;
%end;
%mend loop_counter;
%loop_counter(n=3);
*==============================================================================;
* Pattern 2: %SCAN over a space-delimited list;
*==============================================================================;
%macro summarise_params(ds=adlb, params=ALT AST BILI);
%local i param;
%let i = 1;
%let param = %scan(¶ms., &i., %str( ));
%do %while(¶m. ne );
proc means data=&ds. n mean std min max;
where paramcd = "¶m.";
var aval;
title "Summary for ¶m.";
run;
%let i = %eval(&i. + 1);
%let param = %scan(¶ms., &i., %str( ));
%end;
%mend summarise_params;
%summarise_params(params=ALT AST BILI);- SAS macros support two loop styles: a counted
%DO i = 1 %TO nand a conditional%DO %WHILE. - The counted loop is straightforward:
%do i = 1 %to &n.repeats the body exactlyntimes, incrementing&ieach pass. - For iterating over a list of values, we combine
%SCANwith%DO %WHILE. %scan(¶ms., &i., %str( ))extracts thei-th word from the space-delimited string. When it runs out of words, it returns blank.- The
%DO %WHILE(¶m. ne )condition stops the loop once%SCANreturns an empty string. - Inside the loop body, we run a
PROC MEANSfiltered to the current¶m.value — one output block per PARAMCD. %LOCAL i param;declares the loop variables as local to the macro, preventing them from leaking into the global symbol table.- After running, we see three separate PROC MEANS outputs: one for ALT, one for AST, one for BILI.