Hello,
I want to create a macro that needs to identify whether a macro variable previously defined contains certain variable. For example, I first created the macro variable 'covariates' as shown below:
%let covariates = seq weekend sex;
Then, the following macro runs a block of code depending whether the variable 'sex' is included in &covariates or not (See red text below).
%macro test;
*The two lines of code below are to show what I, not how;
"if &covariates contains SEX" then &sex=1;
else &sex=0;
%if %sysevalf(&sex=1) %then %do;
%end;
%else %do;
%end;
%mend;
Can you please advice?
Thanks a lot.
Use the base function INDEXW to detect the position of a word in a delimited list of words. If not found the result will be zero, so you can use the result as a logical test for presence.
INDEXW is case sensitive so you need to be careful.
Example
%let itemlist = seq weekend sex; %put NOTE: token SEX at position %sysfunc(indexw(%upcase(&itemlist),SEX));
%put NOTE: token WEEKDAY at position %sysfunc(indexw(%upcase(&itemlist),WEEKDAY));
Log
NOTE: token SEX at position 13
NOTE: token WEEKDAY at position 0
Where will this occur? Within a data step, SQL or open code? What should happen in the end, a new variable is being created or a new macro variable? What is the macro variable sex coming from and what value does that contain? Why the duplicate logic as well, is there a specific reason to create that variable rather than go straight into the IF/THEN logic?
As to isolating terms, you can use regular functions like FIND but you need to use SYSFUNC() within the macro language.
Use the base function INDEXW to detect the position of a word in a delimited list of words. If not found the result will be zero, so you can use the result as a logical test for presence.
INDEXW is case sensitive so you need to be careful.
Example
%let itemlist = seq weekend sex; %put NOTE: token SEX at position %sysfunc(indexw(%upcase(&itemlist),SEX));
%put NOTE: token WEEKDAY at position %sysfunc(indexw(%upcase(&itemlist),WEEKDAY));
Log
NOTE: token SEX at position 13
NOTE: token WEEKDAY at position 0
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.