Reputation: 468
I have a dataset (see picture below). I need to fill the stitched_price column. For row 1, I need to use the value from 'price.' This works.
For row 2 onwards, I need to do the following: stitched_price = lag(stitched_price) * (trade_return + 1)
. However, this doesn't work and leaves all rows > 1 blank.
Here is my code:
data test2;
set test;
if _N_ = 1 then stitched_price = price;
else stitched_price = lag(stitched_price) * (1 + trade_return);
run;
I am not sure why this is happening. I understand that there are intricacies involved with using lag in an if statement, but is there a way around this?
Upvotes: 0
Views: 372
Reputation: 21264
Try retain instead:
data test2;
set test;
retain stitched_price;
if _N_ = 1 then stitched_price = price;
else stitched_price = stitched_price * (1 + trade_return);
run;
In general lag doesn't work in conditional blocks. If you did want to use lag, it would be something like follows:
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;
Here's an older post on why lag doesn't work and I'm sure Google has many others: lag function doesn't work in SAS
Upvotes: 2