Reputation: 307
I used the following code to create a new variable that represents the previous value of close_midpoint by separating the different group of _ric.
data test;
set HAVE;
lric=lag(_ric);
if lric=_ric then lclose_midpoint=lag(close_midpoint);
else lclose_midpoint=.;
run;
However, as showing in the following figure, the lag value of close_midpoint in red square equal the last value of close_midpoint in previous _ric group. For example, the lclose_midpoint in the observation 7 should be 4.675, while it is 4.2 in the actual result. So what's the problem in my code? Thanks.
Upvotes: 2
Views: 156
Reputation: 51601
LAG() does not take the value from the previous observation. It makes its own stack and takes the value from the values that were passed to it on previous calls. Since you are only calling LAG() conditionally there is no way for it to find the values you want.
data test;
set HAVE;
by _ric ;
lclose_midpoint=lag(close_midpoint);
if not first._ric then lclose_midpoint=.;
run;
Upvotes: 2
Reputation: 27508
@Tom shows how the lag
is used unconditionally and therefore the side-effect is the value of the prior row.
IFN
can be used to have the same effect as two statements.
data want;
set sashelp.cars;
by make;
MSRP_lag_within_group = ifn ( first.make , . , lag(MSRP) );
keep make model MSRP lMSRP;
run;
Upvotes: 0