/***************************************************************************************************************** SAS file name: lag_function.sas File location: __________________________________________________________________________________________________________________ Purpose: To investigate the Lag Function in SAS Author: Peter Clemmensen Creation Date: 16/12/2019 This program supports the blog post "Investigating the SAS Lag Function By Example" on SASnrd.com *****************************************************************************************************************/ /* Example data */ data have; input id x; datalines; 1 1 1 2 1 3 2 4 2 5 2 6 ; /* Use the lag2 function to initialize a queue with two entries */ data want; set have; lag_x = lag2(x); run; /* Visualize the content and returned value from the lag2 queue */ /* id x Queue content 1 1 [ 1 | . ] Returned value: . 1 2 [ 2 | 1 ] Returned value: . 1 3 [ 3 | 2 ] Returned value: 1 2 4 [ 4 | 3 ] Returned value: 2 2 5 [ 5 | 4 ] Returned value: 3 2 6 [ 6 | 5 ] Returned value: 4 */ /* Conditionally execute the lag function */ data want; set have; if mod(_N_, 2) = 0 then y = lag2(x); run; /* Visualize the content and returned value from the lag2 queue */ /* id x Queue content 1 1 [ . | . ] 1 2 [ 2 | . ] Returned value: . 1 3 [ 2 | . ] 2 4 [ 4 | 2 ] Returned value: . 2 5 [ 4 | 2 ] 2 6 [ 6 | 4 ] Returned value: 2 */ /* The ifc function executes the lag2 function regardless of whether the condition is true */ data want; set have; y = ifn(mod(_N_, 2) = 0, lag2(x), .); run; /* Handling By Groups */ /* Undesired result */ data want; set have; by id; if first.id=0 then lagx=lag(x); run; /* Correct result */ data want; set have; by id; lagx = ifn(first.id, ., lag(x)); run;