Search code examples
sassas-macro

SAS: including macro reference in output?


In SAS, is there a way to reference a macro in declaring an explicit output? It gives me an error when I use the code below, which tries to use the macro "&fname" as the output name declaring at the beginning of the data step. (As a bonus, is there a way to declare the names of the output data sets as some sort of loop, so I don't have to type cd2002, cd2003, etc..).

data cd2002 cd2003 cd2004 cd2005;
    set cd;
    do i = 2002 to 2005;
        %let fname=cats(cd,i);
        if year=i then do; output &fname; end;
    end
run;

Solution

  • Write a macro routine. This is a way to have SAS "write" code for you. There is a macro processor that expands the code and then submits it to the main interpreter.

    %macro split_cd(to,from);
    %local i;
    data
       %do i=&to %to &from;
          cd&i
       %end;
    ;
    set cd;
    %do i=&to %to &from;
          if year=&i then output cd&i;
    %end;
    run;
    %mend;
    

    Use the mprint option to see what code was generated and sumbitted:

    options mprint;
    %split_cd(2002,2005)