SAS (Base SAS)+
*==============================================================================;
* Create sample ADSL data;
*==============================================================================;
data adsl;
input usubjid $ trt01p $ age sex $ race $12.;
datalines;
SUBJ001 Placebo 67 M White
SUBJ002 DrugA 59 F Black
SUBJ003 Placebo 72 F White
SUBJ004 DrugA 65 M Asian
SUBJ005 Placebo 60 F White
SUBJ006 DrugA 55 M Black
;
run;
*==============================================================================;
* Macro with conditional logic based on variable type;
*==============================================================================;
%macro analyse(ds=adsl, var=, type=);
%if %upcase(&type.) = CONT %then %do;
*--- Continuous: means, std, min, max ---;
proc means data=&ds. n mean std min max;
var &var.;
title "Continuous summary: %upcase(&var.)";
run;
%end;
%else %if %upcase(&type.) = CAT %then %do;
*--- Categorical: frequency counts ---;
proc freq data=&ds.;
tables &var. / nocum nopercent;
title "Categorical summary: %upcase(&var.)";
run;
%end;
%else %do;
%put ERROR: [analyse] type=&type. is not valid. Use CONT or CAT.;
%end;
%mend analyse;
*==============================================================================;
* Call with different types;
*==============================================================================;
%analyse(var=age, type=cont);
%analyse(var=sex, type=cat);
%analyse(var=race, type=cat);
%analyse(var=age, type=other);- To branch inside a SAS macro, we use
%IF condition %THEN %DO; ... %END;followed by optional%ELSE %IFand%ELSEblocks. %upcase(&type.)converts the parameter to uppercase before comparing, so the call works whether the user passescont,CONT, orCont.- The continuous branch runs
PROC MEANSto produce N, mean, std, min, and max β the standard descriptive statistics for a numeric variable. - The categorical branch runs
PROC FREQwithTABLESto produce frequency counts for each level of the variable. - The final
%ELSEblock is a safety net: it writes an error to the log if the user passes an unrecognised type, preventing silent failures. %PUT ERROR:writes to the log with the red ERROR prefix, making it easy to spot in a long log file.- After running, we see a PROC MEANS table for AGE, PROC FREQ tables for SEX and RACE, and an error message for the invalid type call.