问题
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?
回答1:
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).
回答2:
You're mixing macro & datastep syntax incorrectly...
You need a macro-loop (%DO
instead of do
) to generate the datastep code (i.e. lag1-lag50), and macro-loops need to be within a macro.
%MACRO LAGLOOP ; data out ; set in ; %DO J = 1 %TO 50 ; lag_&J = lag&J(x) ; %END ; run ; %MEND ; %LAGLOOP ;
来源:https://stackoverflow.com/questions/25898255/sas-do-loops-use-loop-variable-inside-the-loop-to-create-lagged-variables