Sample 25938: Using the LAG function to obtain information from previous observation(s)
The sample code on the Full Code tab illustrates how to use the LAG function to create lagged values of a variable.
See also
Obtaining the previous value of a variable within a BY-Group
and
Use the LAG function to conditionally carry information down a data set
.
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
/* Sample 1: Create a single lag of one variable */
data one;
input x;
lagonce=lag(x);
datalines;
1
2
3
4
5
;
proc print data=one;
title 'Sample1: Single lag of one variable';
run;
/* Sample 2: Create multiple lags of one variable */
data two;
input x;
lag1=lag(x);
lag2=lag2(x);
datalines;
1
2
3
4
5
;
proc print data=two;
title 'Sample 2: Multiple lags of one variable';
run;
/* Sample 3: Create a single lag of one variable within a BY-Group */
/* */
/* See also: */
/* Sample 140: Obtaining the previous value of a variable within */
/* a BY-Group */
/* Sample 108: Use the LAG function to conditionally carry */
/* information down a data set */
data three;
input group $ x;
datalines;
a 1
a 2
a 3
b 1
b 2
b 3
b 4
;
data final;
set three;
by group;
lagx=lag(x);
/* Note the LAG function is executed outside the IF condition. */
/* On the first member of the BY-Group, the variable created */
/* with the LAG function is reset to missing. */
if first.group then lagx=.;
run;
proc print data=final;
title 'Sample 3: Single lag of one variable within a BY-Group';
run;
These sample files and code examples are provided by SAS Institute
Inc. "as is" without warranty of any kind, either express or implied, including
but not limited to the implied warranties of merchantability and fitness for a
particular purpose. Recipients acknowledge and agree that SAS Institute shall
not be liable for any damages whatsoever arising out of their use of this material.
In addition, SAS Institute will provide no support for the materials contained herein.
Sample1: Single lag of one variable
Obs x lagonce
1 1 .
2 2 1
3 3 2
4 4 3
5 5 4
Sample 2: Multiple lags of one variable
Obs x lag1 lag2
1 1 . .
2 2 1 .
3 3 2 1
4 4 3 2
5 5 4 3
Sample 3: Single lag of one variable within a BY-Group
Obs group x lagx
1 a 1 .
2 a 2 1
3 a 3 2
4 b 1 .
5 b 2 1
6 b 3 2
7 b 4 3
Use the LAG function to create lagged values of a variable.
Type: | Sample |
Topic: | SAS Reference ==> DATA Step SAS Reference ==> Functions ==> Special
|
Date Modified: | 2005-12-17 03:02:48 |
Date Created: | 2005-07-27 08:55:08 |
Operating System and Release Information
SAS System | Base SAS | All | n/a | n/a |