buffalol
buffalol

Reputation: 73

Calculating moving averages in SAS

I am relatively new to SAS and need to calculate a moving average based on a variable. I've made some example code to explain:

DATA testData;
input shop year sales;
datalines;
01 01 20000
01 02 23500
01 03 21020
02 01 23664
02 02 15420
02 03 14200
03 01 25623
03 02 12500
03 03 20030
;
run; 

DATA average;
retain y 0;
set testData;
y = y + sales;
avg = y/_n_;
run;

This gives me the average for all my sales. What I want to do is only get the averages per shop and based on the last year and then on all years of that shop. Then to start again for the next shop. Hopefully this makes some kind of sense. I don't want the moving average of any of shop 1's years to affect the average in shop 2.

Upvotes: 0

Views: 3062

Answers (1)

Vasilij Nevlev
Vasilij Nevlev

Reputation: 1449

What you need to do is to reset your average every time you start counting a new shop. You also need to use your own record counter. Here is the improved code:

DATA testData;
    input shop year sales;
    datalines;
01 01 20000
01 02 23500
01 03 21020
02 01 23664
02 02 15420
02 03 14200
03 01 25623
03 02 12500
03 03 20030
;
run;

PROC SORT DATA=WORK.TESTDATA
    OUT=Sorted;
    BY shop year;
RUN;

DATA average (drop=n);
    set Sorted;
    by shop; 
    if first.shop then
        do;
            y = 0;
            n = 0;
        end;
    n + 1;
    y + sales;
    avg = y/n;
run;

Also, notice that the retain statement is not necessary is you express your sum statement is expressed as "i + y" instead of "i=i+y".

For more information about group by, see this SAS Support doc.

Result:

Result

Upvotes: 2

Related Questions