使用宏和数组来延迟SAS中的一组变量

时间:2013-10-12 21:09:08

标签: sas

我尝试使用宏和数组来按组(id)滞后一堆变量。我的步骤是: 1.滞后所有变量(组无关紧要) 2.用.

替换误滞单元格

但我发现我的代码有问题并且感谢任何建议。

以下是数据:

data old;
  input id sale capx profit;
datalines;
1   11  111 1111
1   12  112 1112
1   13  113 1113
1   14  114 1114
1   15  115 1115
1   16  116 1116
1   17  117 1117
2   21  221 2221
2   22  222 2222
2   23  223 2223
3   31  331 3331
3   32  332 3332
3   33  333 3333
3   34  334 3334
4   41  441 4441
4   42  442 4442
4   43  443 4443
4   44  444 4444
4   45  445 4445
4   46  446 4446
;
run;

代码:

 data new;
 set old;
 run;

%macro lag_var(dataset, lag);
  proc sort data=&dataset;by id;
  data &dataset;
    set &dataset;
    by id;
    array vs(3) sale capx profit;
    %do j=1 %to 3;
            %do i=1 %to &lag;
            lag&j&i=lag&i(vs(&j));

            if first.id then 
            do;
            count=1;
            lag&j&i=.;
            end;
            count+1;
            if (not first.id and count<=&i) then
            do;
            lag&j&i=.;
            count+1;
            end;
            %end;
    %end;
  run;
%mend lag_var;

%lag_var(new,5)

当前输出(错误): enter image description here

我的预期结果: enter image description here

DomPazz的输出: enter image description here

1 个答案:

答案 0 :(得分:2)

后来的群体保持其价值的原因是你过度增加count

我认为这可以满足您的需求:

%macro lag_var(dataset, lag);
  proc sort data=&dataset;by id;
  data &dataset;
    set &dataset;
    by id;
    array vs(3) sale capx profit;
    %do j=1 %to 3;
            %do i=1 %to &lag;
            lag&j&i=lag&i(vs(&j));
            %end;
    %end;

    if first.id then do;
       count=0;
       %do j=1 %to 3;
          %do i=1 %to &lag;
             lag&j&i=.;
          %end;
       %end;
    end;

    count+1;

    %do j=1 %to 3;
       %do i=1 %to &lag;

          if (not first.id and count<=&i) then do;
               lag&j&i=.;
            /*count+1;*/
          end;
       %end;
    %end;
  run;
%mend lag_var;

编辑:将计数的初始化从1更改为0.

相关问题