Lesson 11, Part 4: Generating Parts of an SAS Statement Using a Macro¶
The macro below conditionally adds a variable (based on the parameter value to the macro call) in the PROC FREQ table statement.
- %sysfunc(ifc(condition, value_if_true, value_if_false)) is a way to do inline logic.
- %length(&row_var) checks if row_var is provided.
- If yes → row_var * smoking_status
- If no → just smoking_status
%let tbl = %sysfunc(ifc(%length(&row_var), &row_var * , ))smoking_status;
If row_var is empty → tbl = smoking_status
If row_var is specified → tbl = row_var * smoking_status
In [53]:
* Ex15_macro_part_of_SAS_statement.sas;
ods html close; /* close default HTML to avoid clutter, optional */
options nocenter nodate nonumber symbolgen;
%macro run_freq(row_var);
/* Build table expression dynamically */
%let tbl = %sysfunc(ifc(%length(&row_var), &row_var * , ))smoking_status;
/* Create a small dataset to display macro variable */
data tbl_debug;
length info $50;
info = "&tbl";
run;
/* Print macro variable inline in Jupyter notebook */
proc print data=tbl_debug noobs label;
label info="DEBUG: TBL";
run;
/* Run PROC FREQ */
proc freq data=sashelp.heart;
tables &tbl;
run;
%mend run_freq;
The SAS System E3969440A681A2408885998500000051
In [55]:
%run_freq()
%run_freq(sex)
%run_freq(Weight_Status)
| DEBUG: TBL |
|---|
| smoking_status |
The FREQ Procedure
| Smoking Status | ||||
|---|---|---|---|---|
| Smoking_Status | Frequency | Percent | Cumulative Frequency |
Cumulative Percent |
| Frequency Missing = 36 | ||||
| Heavy (16-25) | 1046 | 20.22 | 1046 | 20.22 |
| Light (1-5) | 579 | 11.19 | 1625 | 31.41 |
| Moderate (6-15) | 576 | 11.13 | 2201 | 42.55 |
| Non-smoker | 2501 | 48.35 | 4702 | 90.90 |
| Very Heavy (> 25) | 471 | 9.10 | 5173 | 100.00 |
| DEBUG: TBL |
|---|
| sex *smoking_status |
The FREQ Procedure
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||
| DEBUG: TBL |
|---|
| Weight_Status *smoking_status |
The FREQ Procedure
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||
In [ ]:
%showLog
In [ ]: