Checking for a New Subject Number Using a LAG Function - SAS Programming

To prevent the previous situation from happening, you cannot merely rely on the presence of a value for DOB.Instead, you need to set the variable OLD_DOB equal to DOB each time you read data from what you know to be a new subject.

How do you tell when you have reached a new subject? One approach is to compare the current value of SUBJ to the previous value by using the LAG function.

This function is another powerful and easily misunderstood (and misused) feature of the SAS System.The LAG function works by returning the value of its argument the last time it (the LAG function) was executed. If you execute the LAG function for every observation, its value is the value of the variable from the previous observation.The statement

IF SUBJ NE LAG(SUBJ) THEN OLD_DOB=DOB; 0

sets OLD_DOB equal to DOB each time a new subject is encountered (even if DOB is missing). Here is the code that works:

Example

DATA WORKS;
RETAIN OLDJX)B;
INFILE 'HTWT'j
INPUT 31 SUBJ $2.
§7 DOB MMDDYY8.
€17 WEIGHT 3.?
*CHECK IF WE HAVE A NEW SUBJECT NUMBER. IF SO,
SET OLDJDOB TO THE DOB VALUE FOR THE NEW SUBJECT;
IF SUBJ NE LAG{SUBJ) THEN OLDJX)B=DOB; »
ELSE DOB*OLDJ>OB;
FORMAT DOB MMDDYY8.?
DROP OLDJ>OB;
RUN;
PROC PRINT DATA^WORKS;
TITLE1 'Correct DOB Solution';
RUN;

The correct results are shown in Output 6.

Output from Example - Checking for a New Subject Number Using a LAG Function

Output from Example - Checking for a New Subject Number Using a LAG Function


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

SAS Programming Topics