Dear all,
Suppose that I have the following macro list variable:
%let list = a1, a2, a3, a4, a5;
If I want to create another macro variable selecting the elements a1, a2 and a3 how can I do this?
Thanks.
AFM.
If you need to keep the commas, here's a trick that might work. (I can't test it at the moment so that part is up to you).
%let list = a1, a2, a3, a4, a5;
%macro first3;
%global newmacrovar;
%let newmacrovar=;
%local k;
%do k=1 %to 3;
%let newmacrovar = &newmacrovar %scan("&list", &k, ", ");
%end;
%mend first3;
I'm omitting the commas from the new macro variable, but they can be added with a single additional line of code:
%do k=1 %to 3;
%let newmacrovar = &newmacrovar %scan("&list", &k, ", ");
%if &k < 3 %then %let newmacrovar = &newmacrovar,;
%end;
You really turned this into a difficult problem by inserting commas into your list. Is there any chance you can go back and change the code so that you get:
%let list = a1 a2 a3 a4 a5;
I agree with @Astounding it's easier without the commas - then check out the %scan macro function which allows you to select the nth element from the list, put that inside a %do loop and you're done....
If you need to keep the commas, here's a trick that might work. (I can't test it at the moment so that part is up to you).
%let list = a1, a2, a3, a4, a5;
%macro first3;
%global newmacrovar;
%let newmacrovar=;
%local k;
%do k=1 %to 3;
%let newmacrovar = &newmacrovar %scan("&list", &k, ", ");
%end;
%mend first3;
I'm omitting the commas from the new macro variable, but they can be added with a single additional line of code:
%do k=1 %to 3;
%let newmacrovar = &newmacrovar %scan("&list", &k, ", ");
%if &k < 3 %then %let newmacrovar = &newmacrovar,;
%end;
I appreciate your solution.
I solved the problem using the %do loop, but I thought there were some function like scan that select the k-th element from a list macro variable.
%let list = a1, a2, a3, a4, a5;
%let want=%sysfunc(prxchange(s/\W+\w+\W+\w+$//,1,%nrbquote(&list)));
%put &want ;
Thank you very much for your answer!
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.