EZ Study

Actuarial Biology Chemistry Economics Calculators Confucius Engineer
Physics
C.S.

How to get the dynamic number of macro parameters?

Question: when we use a macro to run repeated processes, we may have the situation with dynamic number of macro parameters.

In other words, sometimes the macro is called: %macroname(keyvar,var1,var2), and some other time it is called %macroname(keyvar,var1,var2,var3);

How can we set up a macro with dynamic number of macro parameters?

Answer: In stead of putting the macro parameters in the above form,
we can change a little bit:
%macroname(keyvar,var1_var2) ==> %macroname(keyvar,var1_var2_var3).

In other words, we try to read the dynamic number of (sub)-parameters from the second parameter, and it's fixed.

Here is the code to grab those parameters in the macro(say the parameter: ids=id1_id2_id3_id4_id5_id6_id7_id8_id9_id10):

%macro macroname(keyvar,ids);

data _null_;
call symputx('num_of_id_by_symputx',countw("&ids.",'_'));
run;

%put &num_of_id_by_symputx.;

==>: it shows: 10 (number of words in expression is 10, delimiter is '_').

/***************************************************/
data test;
do count=1 to &num_of_id_by_symputx.;
word = scan("ids.",count,'_');
output;
end;
drop count; run;

proc sql;
select word into: id1-:id%eval(&num_of_id_by_symputx.)
from test; quit;
... ...
/***************************************************/

%mend;

We have successfully grabbed those 10 ids into 10 macro variables id1, id2,..., id10, we are free to use them later.

When assigning values to macro variables, watch out for the quote sign, easy to make mistakes. Also notice the difference from %let, example:

%let ids=id1_id2_id3_id4_id5_id6_id7_id8_id9_id10;
%let num_of_id_by_let=countw("&ids.",'_');
%put &num_of_id_by_let.;

==>: it shows: countw("id1_id2_id3_id4_id5_id6_id7_id8_id9_id10",'_')