Production Ready Macros for SAS Application Developers
https://github.com/sasjs/core
mp_prevobs.sas File Reference

Enables previous observations to be re-instated. More...

Go to the source code of this file.

Detailed Description

Remembers the last X observations by storing them in a hash table. Is a convenience over the use of lag() or retain, when an entire observation needs to be restored.

This macro will also restore automatic variables (such as n and error).

Example Usage:

data example;
  set sashelp.class;
  calc_var=_n_*3;
  %* initialise hash and save from PDV ;
  %mp_prevobs(INIT,history=2)
  if _n_ =10 then do;
    %* fetch previous but 1 record;
    %mp_prevobs(FETCH,-2)
    put _n_= name= age= calc_var=;
    %* fetch previous record;
    %mp_prevobs(FETCH,-1)
    put _n_= name= age= calc_var=;
    %* reinstate current record ;
    %mp_prevobs(FETCH,0)
    put _n_= name= age= calc_var=;
  end;
run;

Result:

mp_prevobs sas

Credit is made to data _null_ for authoring this very helpful paper: https://www.lexjansen.com/pharmasug/2008/cc/CC08.pdf

Parameters
actionEither FETCH a current or previous record, or INITialise.
recordThe relative (to current) position of the previous observation to return.
history=The number of records to retain in the hash table. Default=5
prefix=the prefix to give to the variables used to store the hash name and index. Default=mp_prevobs
Version
9.2
Author
Allan Bowe

Definition in file mp_prevobs.sas.