Saturday, October 30, 2010

SAS - Retain and Lag

In SAS, working inside one observation is easy.
On the contrary, working across observations is complicated.

In this post we will put the basics of two statements that allow to communicate information across registers.
  • RETAIN
With RETAIN, we can save the value of a variable across registers. In the following example, each register will have an additional subject field, with increasing value starting from 0.

data better;
retain subject 0;
subject = subject + 1;
input score 1 score 2;
datalines;
run;


RETAIN presents some problems, specially when dealing with missing values. If a value is missing, RETAIN does not maintain the previous non-missing value.

  • LAG
The LAG function returns the value of its argument the last time it was executed. For example,

if subj ne lag(subj) then old = new;

Here, old only changes when there is a new subject.

No comments:

Post a Comment