BookmarkSubscribeRSS Feed
PeterClemmensen
Tourmaline | Level 20

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!

4 REPLIES 4
XavierBizoux
SAS Super FREQ

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

Xavier BIZOUX
Advisory Technical Architect ● Global Enablement and Learning
Technology Transfer and Governance, R&D
Kurt_Bremser
Super User

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.

ballardw
Super User

Also the DIF function behaves in a similar manner.

PeterClemmensen
Tourmaline | Level 20

Thank you all, very helpful 🙂

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1449 views
  • 1 like
  • 4 in conversation