Not applicable
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.

Super User
Posts: 10,787

## Re: calculate 3 month average

Posted in reply to Jinglefthere

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;

Discussion stats