Search code examples
sassas-macro

SAS: Creating lag variables with a do macro


I'm trying to create 4 new lag variables, each one adding an additional lag. The code below produces only the final lag variable, i.e. after running this code there is a new variable called lag_4, but lag_1, lag_2, and lag_3 are not created. Thanks

%macro makelags; 
%do i=1 %to 4;
data work.test1;
   set work.dataset;
   lag_&i = lag&i(id_number);
run;
%end;
%mend makelags;
%makelags;

Solution

  • You need to loop inside the data step, not outside of it.

    If you were to loop:

    data work.test1;
      set work.dataset;
      %do i = 1 %to 4;
        lag_&i. = lag&i.(id_number);
      %end;
    run;
    

    (The whole datastep can be inside a macro, or just the %do loop).

    The way I'd do it, if I needed a macro (Because, say, the number of lags varies):

    %macro lagme(num_lags=);
      %do _i = 1 %to &num_lags.;
         lag_&_i. = lag&_i.(id_number);
      %end;
    %mend lagme;
    
    data mydata;
      set olddata;
      %lagme(num_lags=4);
    run;