You may already know the use of the MINOPERATOR and MINDELIMITER in the SAS Macro Language. This gives us the flexibility to write code using the IN operator a la in the DATA step. Intervals are not allowed however.
An alternative approach is using a handy little SAS macro ISINLIST:
%macro IsInList(value,list);
%local i j listElement listElements start finish;
%if %sysfunc(notdigit(&value)) %then %do;
%put ERROR: (IsInList) Macro variable value is not numeric.;
0
%return;
%end;
%if &list= %then %do;
%put ERROR: (IsInList) List is empty;
0
%return;
%end;
%if %sysfunc(notdigit(%sysfunc(compress(&list,%str( :))))) %then %do;
%put ERROR: (IsInList) List can only be numbers and intervals;
0
%return;
%end;
%let listElements=%sysfunc(countw(&list,%str( )));
%do i=1 %to &listelements;
%let listElement=%scan(&list,&i,%str( ));
%if %index(&listElement,%str(:)) %then %do;
%let start=%scan(&listElement,1,%str(:));
%let finish= %scan(&listElement,2,%str(:));
%if &start ge &finish %then %do;
%put ERROR: (IsInList) Interval error "&listelement": Start must be < finish;
0
%return;
%end;
%do j=&start %to &finish;
%if &value=&j %then %do;
1
%return;
%end;
%end;
%end;
%else %do;
%if &value=&listelement %then %do;
1
%return;
%end;
%end;
%end;
0
%mend;
Now we can write code like this:
/* do something if MONTH is NOT 1-12 */
%if not %IsInList(&month,1:12) %then...
/* do something if MONTH is 1-12 */
%if %IsInList(&month,1:12) %then ...
/* values combined with interval */
%if %IsInList(&code,7 9 13 15:19) %then ...
The first parameter is a reference to a macro variable.
The second parameter is a list of values and/or intervals. Values are separated by a space and intervals has the form START:END.
Please feel free to use and modify the macro as you like.
Have a nice summer out there 😉
Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.
If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website.
Data Literacy is for all, even absolute beginners. Jump on board with this free e-learning and boost your career prospects.