Personal tools
You are here: Home Software Packages SAS Lag and Dif Functions

Lag and Dif Functions

Use to refer to values in previous observations in event history files.

When processing event history type files it is often desirable to refer to values of a variable in previous observations. To look backwards in a file, use the SAS functions: LAG and DIF.

The LAGn function simply looks back in the file n number of records and allows you to obtain a previous value for a variable and store it in the current observation. 'n' refers to the number of records back in the the file and can be an integer from 1 to 99. In the following example, a new value for variable 'x' is read in each time through the data step. During each iteration of the data step, four new variables are created in each observation. 'a' represents the value that was read in for 'x' 1 record back in the file, 'b' represents the value read in for 'x' 2 records back in the file, 'c' is 'x' 3 records ago and 'd' is 'x' 4 records ago. Note that the lag function will generate missing values in records 1-4. Since, in record one there are no previous records and in record two, although there is one previous value for x, there are no values 2, 3 or 4 records back.


    data temp; 
    input x; 
    a=lag1(x); 
    b=lag2(x); 
    c=lag3(x); 
    d=lag4(x);  
    cards; 
    1 
    2 
    3 
    1 
    4 
    4 
    5 
    6 
    ; 
    run; 
    proc print;
    run;

Obs    x    a    b    c    d

1 1 . . . .
2 2 1 . . .
3 3 2 1 . .
4 1 3 2 1 .
5 4 1 3 2 1
6 4 4 1 3 2
7 5 4 4 1 3
8 6 5 4 4 1

Many times the only thing you want to do with a previous value of a variable is to compare it with the current value to compute the difference. The DIFn function works the same way as LAGn, but rather than simply assigning a value, it assigns the difference between the current value and a previous value of a variable. The statement a=difn(x) tells SAS that 'a should equal the current value of x minus the value x had n number of records back in the file'. Take a look at the output of the following code:


  data temp; 
  input x; 
  a=dif1(x); 
  b=dif2(x); 
  c=dif3(x); 
  d=dif4(x); 
  cards; 
   1 
   2 
   3 
   1 
   4 
   4 
   5 
   6 
   ; 
  run; 
  proc print;
  run; 

  OBS   X   A   B   C   D
1 1 . . . .
2 2 1 . . .
3 3 1 2 . .
4 1 -2 -1 0 .
5 4 3 1 2 3
6 4 0 3 1 2
7 5 1 1 4 2
8 6 1 2 2 5

Can you look forward in the file? No, not with a function. To look ahead requires some more complicated programming.

Document Actions

Copyright ©2009, The Pennsylvania State University | Privacy and Legal Statements
Contact the Help Site Administrator | Last modified Aug 13, 2008 | Weblion Partner