/* USE one do UNTIL */

data d;
input id name$ price;
cards;
1 A 10
1 A 12
1 A 9
1 A 3
1 A 10
1 A 12
1 A 9
1 A 30
1 A 15
1 A 19
1 A 20
1 A 22
1 A 29
1 A 21
1 A 27
1 A39
2 B 4
2 B 5
2 B 6
2 B 7
8 C 1
8 C 1
8 C 3
;
run;
 
PROC SORT DATA=d OUT=d; BY id;
 
%let M_num=7;
%let M_half=3;
 
data d1;
 set d end=eof;
 ser=_N_;
 if (eof) then do ;
  output;
  price=.;
  do i=1 to &M_half; * need 2 筆DUMMY row, ser++, mv sec=. ;
     ser=ser+1;
     output;
   end;
 end;
 else output;
 drop i;
run;
* ======================= ;
 
data MAVG7;
    set d1(rename=(id=b_id name=b_name price=b_price ser=b_ser));
 
   array vals{&M_num} vval1-vval&M_num;
   array aID{&M_num} aid1-aid&M_num;
   retain vals;
   retain aID;
   retain ttt &M_half;
   retain vals;
  by b_id; *useless for this case;
 
do until(flag=1); /* flag is important to control the condition to next row */
        set d1 end=eof;
        vals{mod(ser-1,&M_num)+1}=price; /* vals aid as ring buffer to capture the price and the id at the same time */
        aid{mod(ser-1,&M_num)+1}=id;
 
      if ser=b_ser+&M_half then
        do;
          flag=1;
          sum=0;
          cnt=0;
          do i=1 to &M_num;
             if (b_Id=aid{i}& aid{i}^=.  & vals{i} ^=. ) then do;
                sum=sum+vals{i};
                cnt=cnt+1;
           end;
           if cnt>0 then do;
              mavg_out=sum/cnt;
           end;
           else mavg_out=.;
       end;
       output;
 
        end; * ser=2;
     end; *until set d1 ; 
 
  keep b_id  b_price b_ser sum mavg_out  vval1-vval5  ser  ;
  *  keep a_id  a_price a_ser sum   vval1-vval5 b_ser ser  ; *debug ;
  *   keep a_id  a_price a_ser sum   vval1-vval5 aID1-aid5 b_ser ser  ; *debug;
 
run;
 
相關文章:
             

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 cianfen 的頭像
    cianfen

    cianfen的部落格

    cianfen 發表在 痞客邦 留言(0) 人氣()