Using Caution When Coding with RETAIN - SAS Programming

This example shows one of the pitfalls you can encounter when using RETAIN.Suppose you have recorded the date of birth and weight of each subject on three different weigh-ins.However,the date of birth was only recorded at the first weigh-in, and you were a little sloppy in your data collection and failed to get it for one of your subjects.You want to create a SAS data set that contains the subject's date of birth and weight in each observation.If any data are missing, they should be so noted. Here is the raw data file:

Using Caution When Coding with RETAIN

Here is a program that has all good intentions but doesn't give you exactly what you want:

Example

DATA DANGER;
RETAIN OLDJXJBj H
INFILE 'HTWT'j
INPUT 81 SUBJ $2»
«7 DOB MMDDYY8.
%ll WEIGHT 3.?
IP DOB NE . THEN OLD_DOB=DOBj 0 * SET OLD_DOB TO DOB ;
ELSE DOB=OI*DJ)OBj €> * SO WE CAN j
FORMAT DOB MMDDYY&.J * REMEMBER IT ;
DROP OLD_DOB?
RON?
PROC PRINT DATA=DANGER;
TITLE1 'Incorrect DOB Solution*j
RON;

Here is the output:

Output from Example - Using Caution When Coding with RETAIN

Output from Example - Using Caution When Coding with RETAIN

What Went Wrong?

The program was supposed to work in the following way: For each observation being added to the data set, DOB is read in from the raw data and OLD_DOB is created via a RETAIN statement O.In this example, you do not supply an initial value for the retained variable .

As each record is built for the data set, the values of DOB and OLD_DOB have an effect on each other.If DOB as read in is not missing (a new subject), then OLD_DOB is set to DOB @.If DOB is missing (another record for the previous subject),then DOB is set to the retained value of OLD_DOB ©. Sounds reasonable. So what went wrong? Since DOB was missing entirely for Subject 3, the retained value of OLD_DOB for Subject 2 was used (again).


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

SAS Programming Topics