DATA Step, Macro, Functions and more

Lag Logic

Reply
PROC Star
Posts: 734

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

Hi,

 

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:

 

http://support.sas.com/resources/papers/proceedings09/055-2009.pdf

 

Have a good day

Super User
Posts: 7,762

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
Super User
Posts: 11,343

Re: Lag Logic

Posted in reply to KurtBremser

Also the DIF function behaves in a similar manner.

PROC Star
Posts: 734

Re: Lag Logic

Thank you all, very helpful Smiley Happy

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