SAS utilities for dynamic lead/lag value access.
Purpose:
Creates shifted copies of variable var by looking up the value from the
same dataset at offset rows based on row numbers. Negative offset = lag,
positive offset = lead, offset=0 points to the current row.
Parameters:
dataset= Input dataset name (REQUIRED). Typically, specify the exact same
dataset as the one used in the DATA step SET statement;
var= Target variable to shift/copy (REQUIRED)
offset= Integer only. Negative=lag, Positive=lead, default -1. Decimals not allowed
id= Optional group ID (SINGLE variable only). When specified, the dataset
MUST be pre-sorted and contiguous by `id`
Assumptions & Constraints:
offsetmust be an integer (no decimals)idsupports ONLY one variable (no composite keys)- If
idis provided, the input must be sorted byidand records must be contiguous - Row-number-based lookup: with
id, shifts occur within the sameid;
withoutid, shifts use the physical order of the dataset - Missing is returned when the target row does not exist
Output (naming convention):
- offset<0: &var._prev_abs(offset)
- offset>0: &var._next_abs(offset)
- offset=0: &var._next_0 (by current implementation)
Examples:
data a;
set sashelp.class(keep=name);
%laglead(dataset=sashelp.class, var=name, offset=-1);
%laglead(dataset=sashelp.class, var=name, offset=+2);
run;
data b;
SUBJID="A";VISITNUM=1;AVAL=10;output;
SUBJID="A";VISITNUM=1;AVAL=20;output;
SUBJID="A";VISITNUM=1;AVAL=30;output;
SUBJID="A";VISITNUM=1;AVAL=40;output;
SUBJID="B";VISITNUM=1;AVAL=11;output;
SUBJID="B";VISITNUM=1;AVAL=21;output;
SUBJID="B";VISITNUM=1;AVAL=31;output;
run;
data c;
set b;
%laglead(
dataset=b
,var=AVAL
,offset= -1
,id=SUBJID
);
%laglead(
dataset=b
,var=AVAL
,offset= +1
,id=SUBJID
);
run;
0.1.0(15Auguat2025): Initial version
The package is built on top of SAS Packages Framework(SPF) developed by Bartosz Jablonski.
For more information about the framework, see SAS Packages Framework.
You can also find more SAS Packages (SASPacs) in the SAS Packages Archive(SASPAC).
First, create a directory for your packages and assign a packages fileref to it.
filename packages "\path\to\your\packages";Secondly, enable the SAS Packages Framework. (If you don't have SAS Packages Framework installed, follow the instruction in SPF documentation to install SAS Packages Framework.)
%include packages(SPFinit.sas)Install SAS package you want to use with the SPF's %installPackage() macro.
-
For packages located in SAS Packages Archive(SASPAC) run:
%installPackage(packageName)
-
For packages located in PharmaForest run:
%installPackage(packageName, mirror=PharmaForest)
-
For packages located at some network location run:
%installPackage(packageName, sourcePath=https://some/internet/location/for/packages)
(e.g.
%installPackage(ABC, sourcePath=https://github.com/SomeRepo/ABC/raw/main/))
Load SAS package you want to use with the SPF's %loadPackage() macro.
%loadPackage(packageName)