简体   繁体   中英

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.

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:

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM