Search code examples
sasretaindatastep

SAS retain value and assign to new variable


I have the following data

EMPID   XVAR    SRC 
ABC     PER1    1   
ABC             2   
XYZ     PER1    1   
XYZ             2   
LMN     PER1    1   
LMN             2   
LMN     PER2    1   
LMN             2   
LMN             2   
LMN     PER3    1   
LMN             2   

I need to create a new variable _XVAR for records where SRC=2 based on the value for XVAR on the previous record (where SRC=1)

The output should be like:

EMPID   XVAR    SRC  _XVAR
ABC     PER1    1     
ABC             2     PER1
XYZ     PER1    1   
XYZ             2     PER1
LMN     PER1    1   
LMN             2     PER1
LMN     PER2    1   
LMN             2     PER2
LMN             2     PER2
LMN     PER3    1   
LMN             2     PER3

I am trying the following, but it isnt working;

data t003;
set t003;
by EMPID;
retain XVAR;
if SRC eq 2 then _XVAR=XVAR;
run;

Solution

  • It can also be done by saving the XVAR in a new variable (last_XVAR), retaining it and dropping it (you dont want it in the output). Then use that one to assign _XVAR. Note that you need to set last_XVAR after the IF, or the current XVAR is used in the assignment of _XVAR.

    Your code, edited:

    data t003;
        set t003;
        by EMPID;
    
        length _XVAR last_XVAR $ 10;
    
        if SRC eq 2 then _XVAR = last_XVAR;
    
        last_XVAR = XVAR;
        retain last_XVAR;
        drop last_XVAR;
    run;