Search code examples
saslagretaindatastep

sas - lag by acct id?


Not sure if I need to use lag for this. But here's what I want to do.

Here is the data I have...

acct    sort_order        type
111111     1            standard
111111     1            standard
111111     2            non-standard
111111     3            other
111111     3            other
222222     2            non-standard
222222     3            other
222222     3            other

This is what I want to end up with...

acct     sort_order  type           want
111111       1     standard       standard
111111       1     standard       standard
111111       2     non-standard   standard
111111       3     other          standard
111111       3     other          standard
222222       2     non-standard   non-standard
222222       3     other          non-standard
222222       3     other          non-standard

I have my data set sorted by acct and sort_order. For each acct, I want to take the first type (based on sort_order) and copy it to each row of that acct. For example, acct 111111 has "standard" as it's first type. I want every observation for acct 111111 to have "standard" as it's type.

I tried doing the following with lag, but it doesn't quite work right...

data want;
set have;
by acct;
want = lag(type);
if first.acct then want = type;
run;

Solution

  • You can use the retain statement to copy each value to the next observation.

    Data want;
        set have;
        by accnt;
        retain want;
        if first.accnt then want = type;
    run;