DATA Step, Macro, Functions and more

Lag Logic

Posts: 1,283

Lag Logic

Hi All.


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?


Thank you!

SAS Employee
Posts: 10

Re: Lag Logic



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

Super User
Posts: 10,280

Re: Lag Logic

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.

Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Super User
Posts: 13,583

Re: Lag Logic

Posted in reply to KurtBremser

Also the DIF function behaves in a similar manner.

Posts: 1,283

Re: Lag Logic

Thank you all, very helpful Smiley Happy

Ask a Question
Discussion stats
  • 4 replies
  • 1 like
  • 4 in conversation