Search code examples
saslag

SAS---the adoption of lag function


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.

enter image description here


Solution

  • 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;