Vlada Pleshcheva
Vlada Pleshcheva

Reputation: 81

SAS MACRO: Create many datasets -modify them - combine them into one within one MACRO without need to ouput multiple datsets

My initial Dataset has 14000 STID variable with 10^5 observation for each. I would like to make some procedures BY each stid, output the modification into data by STID and then set all STID together under each other into one big dataset WITHOUT a need to output all temporary STID-datsets.

I start writing a MACRO:

    data HAVE;
       input stid $ NumVar1 NumVar2;
       datalines;
    a 5 45
    b 6 2
    c 5 3
    r 2 5
    f 4 4
    j 7 3
    t 89 2
    e 6 1
    c 3 8
    kl 1 6
    h 2 3
    f 5 41
    vc 58 4
    j 5 9
    ude 7 3
    fc 9 11
    h 6 3
    kl 3 65
    b 1 4
    g 4 4
    ;
    run;

    /*  to save all distinct values of THE VARIABLE stid into macro variables
        where &N_VAR -  total number of distinct variable values        */

    proc sql;
       select count(distinct stid)
          into :N_VAR
          from HAVE;
       select distinct stid
          into :stid1 - :stid%left(&N_VAR)
          from HAVE;
    quit;

    %macro expand_by_stid;

    /*STEP 1: create datasets by STID*/

            %do i=1 %to &N_VAR.;
                data stid&i;
                    set HAVE;
                    if stid="&&stid&i";
                run;

   /*STEP 2: from here data modifications for each STID-data (with procs and data steps, e.g.)*/

                data modified_stid&i;
                    set stid&i;
                    NumVar1_trans=NumVar1**2;
                    NumVar2_trans=NumVar1*NumVar2;
                run;
            %end; 

    /*STEP 3: from here should be some code lines that set together all created datsets under one another and delete them afterwards*/
        data total;
        set %do n=1 %to &N_VAR.;
        modified_stid&n;
        %end;
        run;

    proc datasets library=usclim;
    delete <ALL DATA SETS by SPID>;
    run;

            %mend expand_by_stid;

            %expand_by_stid;

But the last step does not work. How can I do it?

Upvotes: 0

Views: 138

Answers (1)

Bendy
Bendy

Reputation: 3576

You're very close - all you need to do is remove the semicolon in the macro loop and put it after the %end in step 3, as below:

data total;
  set 
  %do n=1 %to &N_VAR.;
    modified_stid&n
  %end;;
run;

This then produces the statement you were after:

set modified_stid1 modified_stid2 .... ;

instead of what your macro was originally generating:

set modified_stid1; modified_stid2; ...;

Finally, you can delete all the temporary datasets using stid: in the delete statement:

proc datasets library=usclim;
  delete stid: ;
run;

Upvotes: 2

Related Questions