Search code examples
sassas-macro

SAS Do loops: use loop variable inside the loop to create lagged variables


I would like to create variables containing lagged values of a given variable for a large number of lags. How could I do this? I try the following:

data out; 
set in;
do i = 1 to 50;
%let j = i;
lag_&j = Lag&j.(x);
end;
run;

How can I get the loop variable i into the macro variable j or how to use it directly to create the appropriately named variable and for the Lag function?


Solution

  • Chris J answers the question, but here i'll provide my preferred way of doing this.

    %macro lagvar(var=,num=);
      %do _iter = 1 %to &num.;
        lag_&_iter. = lag&_iter.(&var.);
      %end;
    %mend lagvar;
    
    data out;
      set in;
      %lagvar(var=x,num=50); *semicolon optional here;
    run;
    

    This is a more modular usage of the macro loop (and more readable, assuming you use intelligent names - the above is okay, you could do even more with the name if you wanted to be very clear, and of course add comments).