O'Reilly logo

SAS 9.4 Macro Language, 5th Edition by

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Here are the results for example, 4B.
Logs
Log: Example 4A
1 %macro iterm(lst);
2 %let finish=%sysfunc(countw(&lst));
3 %do i = 1 %to &finish;
4 %put %scan(&lst,&i);
5 %end;
6 %mend iterm;
7
8 %iterm(a c e)
a
c
e
Log: Example 4B
180 %macro iterm(beg,end);
181 %do i = %sysfunc(rank(&beg)) %to %sysfunc(rank(&end));
182 %put %sysfunc(byte(&i));
183 %end;
184 %mend iterm;
185 /* Just pass in starting and ending value */
186 %iterm(a,e)
a
b
c
d
e
Example 5: Place All SAS Data Set Variables into
a Macro Variable
Details
This macro uses the ATTRN and VARNAME functions to retrieve all the variables
contained within a SAS data set and places them into one macro variable.
Program
data one;
input x y;
datalines;
1 2
;
%macro lst(dsn);
%local dsid cnt rc;
%global x;
%let x=;
454 Appendix 5 SAS Macro Examples
%let dsid=%sysfunc(open(&dsn));
%if &dsid ne 0 %then %do; %let cnt=%sysfunc(attrn(&dsid,nvars));
%do i = 1 %to &cnt;
%let x=&x %sysfunc(varname(&dsid,&i));
%end;
%end;
%else %put &dsn cannot be open.;
%let rc=%sysfunc(close(&dsid));
%mend lst;
%lst(one)
%put macro variable x = &x;
Program Description
Create a data set.
data one;
input x y;
datalines;
1 2
;
Begin the macro definition that contains one parameter.
%macro lst(dsn);
Create the macro variable named &DSID that uses the OPEN function to open the data
set that is passed to the macro. Use the %IF condition to make sure the data set opened
successfully. If the value is yes, then create the macro variable named &CNT that uses
the ATTRN function with the NVARS argument to return the number of variables that
are contained within the SAS data set.
%local dsid cnt rc;
%global x;
%let x=;
%let dsid=%sysfunc(open(&dsn));
%if &dsid ne 0 %then %do; %let cnt=%sysfunc(attrn(&dsid,nvars));
Use the %DO statement to loop through the number of variables within the SAS data set.
%do i = 1 %to &cnt;
Create the macro variable named &X that uses the VARNAME function to return the
name of a SAS data set variable. The first argument to this function specifies the SAS
data set identifier from the OPEN function. The second argument is the number of the
variable’s position. Each time through the %DO loop the value of &X is appended to
itself.
%let x=&x %sysfunc(varname(&dsid,&i));
End the %DO blocks.
%end;
%end;
Example 5: Place All SAS Data Set Variables into a Macro Variable 455

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required