Search code examples
sasretain

how to retain values in a sas dataset?


I have the following dataset

data have;
input pop$  district$ racemajor$;
cards;
    color   Aberdeen    .
    white   Aberdeen    .
    Black   Aberdeen    .
    Asian   Aberdeen    .
    Black   Adelaid  Yes
    Color   Adelaid     .
    white   Adelaid     .
    Asian   Adelaid     .
    White   Bellvill    .
    black   Bellvill    .
    Asian   Bellvill    .
;
run;

Basically I want to drag the value 'Yes' if racemajor is 'Yes' for the corresponding district so that it looks like the following

data want;
    color   Aberdeen    .
    white   Aberdeen    .
    Black   Aberdeen    .
    Asian   Aberdeen    .
    Black   Adelaid     Yes
    Color   Adelaid     Yes
    white   Adelaid     Yes
    Asian   Adelaid     Yes
    White   Bellvill    .
    black   Bellvill    .
    Asian   Bellvill    .

I know that I can use the first. and retain statement to do this, and I tried the following. However, it does not seem to work.

data want;
set have;
if first.district and racemajor='Yes';
retain racemajor;
run;

Solution

  • try this, although to be safe you should sort the data on district

    data NEW;
    drop test;
    SET HAVE;
    by district;
    retain test;
    if first.district then test = racemajor;
    racemajor=test;
    run;