Published on :
ETL CREATION_INTERNE

Data Manipulation with LAG Functions

This code is also available in: Deutsch Español Français
Awaiting validation
This program starts by creating a 't1' dataset with hardcoded values. It then sorts this data by the 'x' variable. A subsequent Data Step ('t2') uses the LAG function to create a new variable 'z' containing the previous value of 'y'. Finally, a last step ('t3') applies complex conditional logic using comparisons between current and lagged values to modify variables.
Data Analysis

Type : CREATION_INTERNE


Data is created directly in the code via the CARDS statement in the data t1 step.

1 Code Block
DATA STEP Data
Explanation :
Creation of table 't1' with two numeric variables x and y, populated by internal data (CARDS).
Copied!
1DATA t1;
2 INPUT x y;
3 CARDS;
4 1 5
52 6
63 6
77 9
88 10
911 12
10;
11RUN;
2 Code Block
PROC SORT
Explanation :
Sorting table 't1' in ascending order by variable 'x'.
Copied!
1PROC SORT DATA=t1; BY x; RUN;
3 Code Block
DATA STEP Data
Explanation :
Creation of table 't2' from 't1'. The LAG(y) function is used to retrieve the value of 'y' from the previous observation and store it in 'z'.
Copied!
1DATA t2;
2 SET t1 END=b;
3 z=lag(y);
4 /*if x>z or b;
5 proc sort; by decending x;
6 */
7RUN;
4 Code Block
PROC PRINT
Explanation :
Displaying the content of the last created table (t2) in the standard output.
Copied!
1PROC PRINT;RUN;
5 Code Block
DATA STEP Data
Explanation :
Creation of table 't3' from 't2'. Applies conditional modifications: if x is less than z, z takes the value of y. Then, y is updated with the maximum between its current value and the previous value of z.
Copied!
1DATA t3;
2 SET t2;
3 IF xTHEN z=y;
4 y=max(y,lag(z));
5 *if y^=z;
6RUN;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.