/***************************************************************************************************************** SAS file name: Leading.sas File location: _________________________________________________________________________________________________________________ Purpose: To present different ways of simulating a LEAD finction Author: Peter Clemmensen Creation Date: 17jul2017 This program supports the blog post "The LEAD Function in SAS" on SASnrd.com *****************************************************************************************************************/ /* Create Sample Data */ data Sample; do time = 1 to 10; value = time * 2; output; end; run; /* Leading in the DATA STEP - Method 1 */ proc sort data = Sample out=Sample_Sort; /* Sort data ascending */ by descending time; run; data Lead_DataStep1; set Sample_Sort; lead1 = lag1(value); /* Look one observation back */ lead2 = lag2(value); /* Look one observations back */ run; proc sort data = Lead_DataStep1; /* Sort data back */ by time; run; /* Leading in the DATA STEP - Method 2 */ data Lead_DataStep2; merge Sample /* Read in Sample data */ Sample(firstobs=2 keep=value rename = (value=lead1)) /* Merge it with itself, but start reading at second obs */ Sample(firstobs=3 keep=value rename = (value=lead2)); /* Merge it with itself, but start reading at third obs */ run; /* Leading with PROC EXPAND */ proc expand data=Sample out=Lead_ProcExpand method=none; id time; convert value=lead1 / transformout=(lead 1); convert value=lead2 / transformout=(lead 2); run; /* By Group Example */ /* Create sample data with groups */ data Group_Sample; do group = 1 to 4; do time = 1 to 4; value = time * 2; output; end; end; run; /* Lead within by-groups with PROC EXPAND */ proc expand data = Group_Sample out=Lead_ProcExpand_Group method=none; by group; id time; convert value=lead1 / transformout=(lead 1); convert value=lead2 / transformout=(lead 2); run;