calculate 3 month average

Reply
N/A
Posts: 1

calculate 3 month average

I am trying to calculate last 3 month average by SAS.

It looks like:

data have;

input item$ month number;

cards;

a   1    1

a   2    1

a   3    2

b   1    3

b   2    3

c   1    5

d   1    5

d   2    2

d   3    1

d   4    2

; run;

I want the output likes:

item  month     ave

a       3        (1+1+2)/3

b       2        (3+3)/2

c       1         5

d       4         (2+1+2)/3

I am very beginner of sas. I do not know how can I calculate this one. Thank you very much.

Grand Advisor
Posts: 9,571

Re: calculate 3 month average

data have;

input item$ month number;

cards;

a   1    1

a   2    1

a   3    2

b   1    3

b   2    3

c   1    5

d   1    5

d   2    2

d   3    1

d   4    2

; run;

data want;

set have;

by item;

if first.item then n=0;

n+1;

lag1=lag(number);

lag2=lag2(number);

if last.item then do;

  if n=1 then avg=number;

   else if n=2 then avg=mean(lag1,number);

    else avg=mean(lag1,lag2,number);

  output;

end;

drop n  lag:  ;

run;

Ask a Question
Discussion stats
  • 1 reply
  • 187 views
  • 0 likes
  • 2 in conversation