11-08-2016 02:39 AM
Can you explain the logic behind the LAG function in the sas data step? How does it know the previous value of some variable? I know the logic behind the data step and that records are read into the PDV and so on..
But I thought that the PDV forgot what data it held once the record was written to the data set?
11-08-2016 03:46 AM
Lag stores the data in a special section of the PDV that is not the current record. This area of the PDV is used to store other information that are not cleared after the PDV for the current observation is cleared.
You can have a look at the following paper for interesting examples of the lag function:
Have a good day
11-08-2016 05:23 AM
Behind the lag() function is a simple FIFO chain, the number of elements in the chain is determined by the function name.
(lag() has one element, lag2() has 2, and so on)
Every time you call lag(), the last element of the chain is retrieved as result, the chain progresses by 1, and the first element receives the current value of the variable.
For the lag() function to work as typically expected, it must therefore not be called conditionally, but has to be used unconditionally once per datastep iteration.