Search code examples
sasconditional-statementssas-macro

How to write concise code for the conditional creation (if…then…) of a set of global macro variables


I've created 14 global macro variables like so:

data _NULL_;
set &medf;
if &class1='Catcher' then call symputx('MedianC',med);
if &class1='Catcher' then call symputx('FrequencyC',_FREQ_);
if &class1='First Baseman' then call symputx('MedianFB',med);
if &class1='First Baseman' then call symputx('FrequencyFB',_FREQ_);
if &class1='Outfielder' then call symputx('MedianO',med);
if &class1='Outfielder' then call symputx('FrequencyO',_FREQ_);
if &class1='Pitcher' then call symputx('MedianP',med);
if &class1='Pitcher' then call symputx('FrequencyP',_FREQ_);
if &class1='Second Baseman' then call symputx('MedianSB',med);
if &class1='Second Baseman' then call symputx('FrequencySB',_FREQ_);
if &class1='Shortstop' then call symputx('MedianS',med);
if &class1='Shortstop' then call symputx('FrequencyS',_FREQ_);
if &class1='Third Baseman' then call symputx('MedianTB',med);
if &class1='Third Baseman' then call symputx('FrequencyTB',_FREQ_);
run;

This seems like an inefficient code, and so I was wondering how I might be able to write this more concisely. I've looked around at the various uses of CALL SYMPUTX, and it seems like I might not need 14 lines of code for 14 global macro variables (i.e., a single line of CALL SYMPUTX might be able to produce multiple macro variables). However, I'm not sure how to retain the conditional nature of my variable creation in fewer lines of code.

If anyone could offer some guidance, I'd greatly appreciate it. Thank you!


Solution

  • Assuming that the first letter of each &class1 'word' can form a suffix to place at the end of the macro variable name, you can complete this task without any need for if-then logic:

    data _NULL_;
    set &medf;
    length suff $8;
    i=1;
    /* Do loop pulls together the first letter of each word */
    /* in the &class1 variable value into a new variable called suff */
    do while (scan(&class1,i) ^= '');
      suff=cats(suff,substr(scan(&class1,i),1,1));
      i+1;
    end;
    
    /* The Median and Frequency words joined to suff make the new macro variable name, */ 
    /* the second argument just holds the values */
    call symputx(cats('Median',suff),med);
    call symputx(cats('Frequency',suff),_FREQ_);
    
    run;