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

☆樱花仙子☆ 提交于 2020-01-04 13:48:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!