简体   繁体   中英

Averages in SAS with date buckets

I've been working with SAS to get some rolling averages, and I can get it to give me those outputs but I want it done by date buckets if possible, which I don't quite know how to do.

Here's some sample data:

Date        Amount   User   Moving Avg
2019-01-01   100      XX1        100
2019-01-02   150      XX1        125
2019-01-03    50      XX1        100
2019-01-20    10      XX1        77.5

2019-01-15   125      XX2        125
2019-01-16    75      XX2        100
2019-01-18    50      XX2        83.3

What I would like is for the averages to be bucketed into date ranges

For example how can I make it show me the average amount for the following week buckets BY the user:

For user XX1: Dec 30th - Jan 5th (would be $100) Jan 20th - Jan 26th (would be $10)

For user XX2: Jan 13th to 19th (would be $83.3)

You could use PROC FORMAT to define custom date ranges and then compute the averages you want.

proc format;
  value datebin
    '01Jan2019'd - '19Jan2019'd  = bin1
    '20Jan2019'd - '26Jan2019'd =  bin2
  ;
run;

proc means data = have ;
  var amt;
  class user d;
  output out = avgs mean = running_avg;
  format d datebin.;
run;

data want;
  set avgs;
  where _type_ = 3;
  keep user d running_avg;
run;

You could write a simple macro to generate the formats that systematically points to a weekly date range starting from any given date.

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