Previous Page | Next Page

Functions and CALL Routines

LAG Function



Returns values from a queue.
Category: Special

Syntax
Arguments
Details
The Basics
Memory Limit for the LAG Function
Examples
Example 1: Generating Two Lagged Values
Example 2: Generating Multiple Lagged Values in BY-Groups
Example 3: Computing the Moving Average of a Variable
Example 4: Generating a Fibonacci Sequence of Numbers
Example 5: Using Expressions for the LAG Function Argument
See Also

Syntax

LAG<n>(argument)


Arguments

n

specifies the number of lagged values.

argument

specifies a numeric or character constant, variable, or expression.


Details


The Basics

If the LAG function returns a value to a character variable that has not yet been assigned a length, by default the variable is assigned a length of 200.

The LAG functions, LAG1, LAG2, ..., LAGn 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 each occurrence of 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 an occurrence of LAGn is executed, the value at the top of its 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 each occurrence 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. An occurrence of the LAGn function that is executed conditionally will store and return values only from the observations for which the condition is satisfied.   [cautionend]

If the argument of LAGn is an array name, a separate queue is maintained for each variable in the array.


Memory Limit for the LAG Function

When the LAG function is compiled, SAS allocates memory in a queue to hold the values of the variable that is listed in the LAG function. For example, if the variable in function LAG100(x) is numeric with a length of 8 bytes, then the memory that is needed is 8 times 100, or 800 bytes. Therefore, the memory limit for the LAG function is based on the memory that SAS allocates, which varies with different operating environments.


Examples


Example 1: Generating Two Lagged Values

The following program generates two lagged values for each observation.

options pagesize= linesize= pageno=1 nodate;

data one;
   input x @@;
   y=lag1(x);
   z=lag2(x);
   datalines;
1 2 3 4 5 6
;

proc print data=one;
   title 'LAG Output';
run;

Output from Generating Two Lagged Values

                                  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).


Example 2: Generating Multiple Lagged Values in BY-Groups

The following example shows how to generate up to three lagged values within each BY group.

/***************************************************************************/
/* This program generates up to three lagged values.  By increasing the    */
/* size of the array and the number of assignment statements that use      */
/* the LAGn functions, you can generate as many lagged values as needed.   */
/***************************************************************************/
options pageno=1 ls=80 ps=64 nodate;

/* Create starting data. */  

data old;
  input start end;
datalines;
1 1
1 2
1 3
1 4
1 5
1 6
1 7
2 1
2 2
3 1
3 2
3 3
3 4
3 5
;

data new(drop=i count);
  set old;
  by start;

  /* Create and assign values to three new variables.  Use ENDLAG1-      */
  /* ENDLAG3 to store lagged values of END, from the most recent to the  */
  /* third preceding value.                                              */   
  array x(*) endlag1-endlag3;
  endlag1=lag1(end);
  endlag2=lag2(end);
  endlag3=lag3(end);

  /* Reset COUNT at the start of each new BY-Group */
  if first.start then count=1;

  /* On each iteration, set to missing array elements   */
  /* that have not yet received a lagged value for the  */
  /* current BY-Group.  Increase count by 1.            */   
  do i=count to dim(x);
    x(i)=.;
  end;
  count + 1;
run;

proc print;
run;
 

Output from Generating Three Lagged Values

                                 The SAS System                                1

              Obs    start    end    endlag1    endlag2    endlag3

                1      1       1        .          .          .   
                2      1       2        1          .          .   
                3      1       3        2          1          .   
                4      1       4        3          2          1   
                5      1       5        4          3          2   
                6      1       6        5          4          3   
                7      1       7        6          5          4   
                8      2       1        .          .          .   
                9      2       2        1          .          .   
               10      3       1        .          .          .   
               11      3       2        1          .          .   
               12      3       3        2          1          .   
               13      3       4        3          2          1   
               14      3       5        4          3          2   

Example 3: Computing the Moving Average of a Variable

The following is an example that computes the moving average of a variable in a data set.

/* Title: Compute the moving average of a variable
   Goal: Compute the moving average of a variable through the entire data set,
         of the last n observations and of the last n observations within a 
         BY-group.
   Input:
*/
options pageno=1 ls=80 ps=64 fullstimer nodate;

data x; 
do x=1 to 10; 
  output; 
  end; 
run;
/* Compute the moving average of the entire data set. */
data avg;
retain s 0;
set x;
s=s+x;
a=s/_n_;
run;
proc print;
run;
/* Compute the moving average of the last 5 observations. */
%let n = 5;
data avg (drop=s);
retain s;
set x;
s = sum (s, x, -lag&n(x)) ;
a = s / min(_n_, &n);
run;
proc print;
run;
/* Compute the moving average within a BY-group of last n observations.
  For the first n-1 observations within the BY-group, the moving average
  is set to missing. */
data ds1;
do patient='A','B','C';
 do month=1 to 7;
  num=int(ranuni(0)*10);
  output;
 end;
end;
run;
proc sort;
by patient;
%let n = 4;
data ds2;
set ds1;
by patient;
retain num_sum 0;
if first.patient then do;
  count=0;
  num_sum=0;
end;
count+1;
last&n=lag&n(num);
if count gt &n then num_sum=sum(num_sum,num,-last&n);
else num_sum=sum(num_sum,num);
if count ge &n then mov_aver=num_sum/&n;
else mov_aver=.;
run;

proc print;
run;

Output from Computing the Moving Average of a Variable

                                 The SAS System                                1

                             Obs     s     x     a

                               1     1     1    1.0
                               2     3     2    1.5
                               3     6     3    2.0
                               4    10     4    2.5
                               5    15     5    3.0
                               6    21     6    3.5
                               7    28     7    4.0
                               8    36     8    4.5
                               9    45     9    5.0
                              10    55    10    5.5
                                 The SAS System                                2

                                Obs     x     a

                                  1     1    1.0
                                  2     2    1.5
                                  3     3    2.0
                                  4     4    2.5
                                  5     5    3.0
                                  6     6    4.0
                                  7     7    5.0
                                  8     8    6.0
                                  9     9    7.0
                                 10    10    8.0
                                 The SAS System                                3

    Obs    patient    month    num    num_sum    count    last4    mov_aver

      1       A         1       4         4        1        .         .    
      2       A         2       9        13        2        .         .    
      3       A         3       2        15        3        .         .    
      4       A         4       9        24        4        .        6.00  
      5       A         5       3        23        5        4        5.75  
      6       A         6       6        20        6        9        5.00  
      7       A         7       8        26        7        2        6.50  
      8       B         1       7         7        1        9         .    
      9       B         2       5        12        2        3         .    
     10       B         3       5        17        3        6         .    
     11       B         4       0        17        4        8        4.25  
     12       B         5       5        15        5        7        3.75  
     13       B         6       9        19        6        5        4.75  
     14       B         7       0        14        7        5        3.50  
     15       C         1       4         4        1        0         .    
     16       C         2       2         6        2        5         .    
     17       C         3       0         6        3        9         .    
     18       C         4       1         7        4        0        1.75  
     19       C         5       2         5        5        4        1.25  
     20       C         6       9        12        6        2        3.00  
     21       C         7       5        17        7        0        4.25  

Example 4: Generating a Fibonacci Sequence of Numbers

The following example generates a Fibonacci sequence of numbers. You start with 0 and 1, and then add the two previous Fibonacci numbers to generate the next Fibonacci number.

data _null_;
   put 'Fibonacci Sequence';
   n=1;
   f=1;
   put n= f=;
   do n=2 to 10;
      f=sum(f,lag(f));
      put n= f=;
   end;
run;

SAS writes the following output to the log:

Fibonacci Sequence
n=1 f=1
n=2 f=1
n=3 f=2
n=4 f=3
n=5 f=5
n=6 f=8
n=7 f=13
n=8 f=21
n=9 f=34
n=10 f=55


Example 5: Using Expressions for the LAG Function Argument

The following program uses an expression for the value of argument and creates a data set that contains the values for X, Y, and Z. LAG dequeues the previous values of the expression and enqueues the current value.

options nodate pageno=1 ls=80 ps=85;

data one;
   input X @@;
   Y=lag1(x+10);
   Z=lag2(x);
   datalines;
1 2 3 4 5 6
;
proc print;
   title 'Lag Output: Using an Expression';
run;

Output from the LAG Function: Using an Expression

                        Lag Output: Using an Expression                        1

                              Obs    X     Y    Z

                               1     1     .    .
                               2     2    11    .
                               3     3    12    1
                               4     4    13    2
                               5     5    14    3
                               6     6    15    4

See Also

Function:

DIF Function

Previous Page | Next Page | Top of Page