Chapter Contents 
Previous 
Next 
LAG 
Category:  Special 
Syntax  
Arguments  
Details  
Examples  
Example 1: Creating a Data Set  
Example 2: Storing Every Other Lagged Value  
See Also 
Syntax 
LAG<n>(argument) 
Details 
The LAG functions, LAG1, LAG2, . . . , LAG100 return values from a queue. LAG1 can also be written as LAG. A LAGn function stores a value in a queue and returns a value stored previously in that queue. Each occurrence of a LAGn function in a program generates its own queue of values.
The queue for LAGn is initialized with n missing values, where n is the length of the queue (for example, a LAG2 queue is initialized with two missing values). When LAGn is executed, the value at the top of the queue is removed and returned, the remaining values are shifted upwards, and the new value of the argument is placed at the bottom of the queue. Hence, missing values are returned for the first n executions of LAGn, after which the lagged values of the argument begin to appear.
Note: Storing
values at the bottom of the queue and
returning values from the top of the queue occurs only when the function is
executed. A LAGn function that is executed conditionally
will store and return values only from the observations for which the condition
is satisfied. See Storing Every Other Lagged Value
.
If the argument of LAGn is an array name, a separate queue is maintained for each variable in the array.
Examples 
The following program creates a data set that contains the values for X, Y, and Z.
options pagesize=25 linesize=64 nodate pageno=1;
data one; input X @@; Y=lag1(x); Z=lag2(x); datalines; 1 2 3 4 5 6 ; proc print; title 'Lag Output'; run;
Lag Output 1 Obs X Y Z 1 1 . . 2 2 1 . 3 3 2 1 4 4 3 2 5 5 4 3 6 6 5 4 
LAG1 returns one missing value and the values of X (lagged
once). LAG2 returns two missing values and the values of X (lagged twice).
This example shows the difference in output when you use conditional and unconditional logic in your program. Because the LAG function stores values on the queue only when it is called, you must call LAG unconditionally to get the correct answers.
options pagesize=25 linesize=64 nodate pageno=1; title 'Store Every Other Lagged Value'; data test; input x @@; if mod(x,2)=0 then a=lag(x); b=lag(x); if mod(x,2)=0 then c=b; label a='(WRONG) a' c='(RIGHT) c'; datalines; 1 2 3 4 5 6 7 8 ; proc print label data=test; run;
Store Every Other Lagged Value 1 (WRONG) (RIGHT) Obs x a b c 1 1 . . . 2 2 . 1 1 3 3 . 2 . 4 4 2 3 3 5 5 . 4 . 6 6 4 5 5 7 7 . 6 . 8 8 6 7 7 
See Also 
Function:

Chapter Contents 
Previous 
Next 
Top of Page 
Copyright 1999 by SAS Institute Inc., Cary, NC, USA. All rights reserved.