【问题标题】:Computing moving average in SAS在 SAS 中计算移动平均线
【发布时间】:2016-03-09 15:31:54
【问题描述】:

我正在尝试使用 SAS 计算在计算中使用预测值的 x 个期间的移动平均值。例如,如果我有一个包含十个变量观察值的数据集,并且我想做一个 3 个月的移动平均线。第一个预测值应该是最后 3 个观测值的平均值,第二个预测值应该是最后两个观测值和第一个预测值的平均值。

【问题讨论】:

标签: sas moving-average


【解决方案1】:

如果您有这样的示例数据:

data input;
infile datalines;
length product $10 period value 8;
informat period yymmdd10.;
format period yymmdd10.;
input product $ period value;
datalines;
car 2016-01-01 10
car 2015-12-01 20
car 2015-11-01 30
car 2015-10-01 40
car 2015-09-01 30
car 2015-08-01 15
;
run;

您可以使用条件左连接输入表本身:

input t1 left join input t2
    on t1.product = t2.product
    and t2.period between intnx('month',t1.period,-2,'b') and t1.period
    group by t1.product, t1.period, t1.value

有了这个你有t1.value作为当前值和avg(t2.value)作为3个月的平均值。要使用ifn() 函数计算 2 个月的平均值,将比上一个时期更早的每个值更改为缺失值:

avg(ifn( t2.period >= intnx('month',t1.period,-1,'b'),t2.value,. ))

完整代码如下所示:

proc sql;
    create table want as
        select t1.product, t1.period, t1.value as currentValue,
            ifn(count(t2.period)>1,avg(ifn( t2.period >= intnx('month',t1.period,-1,'b'),t2.value,. )),.) as twoMonthsAVG,
            ifn(count(t2.period)>2,avg(t2.value),.) as threeMonthsAVG
        from input t1 left join input t2
            on t1.product = t2.product
            and t2.period between intnx('month',t1.period,-2,'b') and t1.period
        group by t1.product, t1.period, t1.value
    ;
quit;

如果我没有足够的记录来计算度量,我还添加了count(t2.perion) 条件以返回缺失值。我的结果集如下所示:

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 2020-02-04
    • 2012-01-21
    • 2011-07-14
    • 2010-09-22
    相关资源
    最近更新 更多