如何创建依赖于自身的SAS变量?

时间:2014-12-23 22:48:28

标签: sas

我有一个数据集(见下图)。我需要填写stitched_price列。对于第1行,我需要使用' price中的值。'这很有效。

对于第2行,我需要执行以下操作:stitched_price = lag(stitched_price) * (trade_return + 1)。但是,这不起作用并且留下所有行> 1空白。

这是我的代码:

data test2;
    set test;
    if _N_ = 1 then stitched_price = price;
    else stitched_price = lag(stitched_price) * (1 + trade_return);
run;

我不确定为什么会这样。我理解在if语句中使用滞后涉及复杂性,但有没有解决方法呢?

This is the result of the code. Prior to running the code, everything is the same except for the absence of the stitched_price variable.

1 个答案:

答案 0 :(得分:2)

请尝试保留:

data test2;
   set test;
    retain stitched_price;
    if _N_ = 1 then stitched_price = price;
    else stitched_price = stitched_price * (1 + trade_return);
run;

通常,滞后在条件块中不起作用。如果您确实想要使用滞后,那么它将如下所示:

data test2;
   set test;
    lag_s=lag(stitched_price);
    if _N_ = 1 then stitched_price = price;
    else stitched_price = lag_s * (1 + trade_return);
run;

这里有一篇关于为什么滞后不起作用的老帖子,我确信Google还有很多其他人: lag function doesn't work in SAS

相关问题