I'm wondering how I can extract an item from a list contained in a macro variable. I know I can do something like this using arrays inside of a data step, but am seeking a way to do this outside of a data step.
I've included a simplified example, in which I create a macro variable containing a list and want to extract the 2nd item.
%let list = dog cat mouse; %put &list$2; /*want this to return cat/*
%put &list$2;
is not really the syntax you want. It writes to the log a string which is your variable &list with $2 appended.
To extract words from a string, you want to use the %scan macro function.
%put %scan(&list,2);
%put &list$2;
is not really the syntax you want. It writes to the log a string which is your variable &list with $2 appended.
To extract words from a string, you want to use the %scan macro function.
%put %scan(&list,2);
What do you consider the second "item"?
A macro variable is just a string of characters.
If you want to treat the macro variable as a space delimited list of values then you can use the %SCAN() function
%let second=%scan(&list,2,%str( ));
Or if you use the macro variable value to generate actual SAS code you can then use the SCAN() function.
second = scan("&list",2,' ');
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.