Search code examples
arraysif-statementsasretain

Retain the value of a variable within a group in SAS


I want to create a variable Var2 that is equal to 1 starting at the first observation Var1 is equal to 1 and Var2 is equal to 1 until the end of the by group defined by ID. Here is the minimal working example:

ID Year Var1
1 1 .
1 2 0
1 3 .
1 4 1
1 5 .

And I want to create the following output:

ID Year Var1 Var2
1 1 . .
1 2 0 0
1 3 . 0
1 4 1 1
1 5 . 1

My current code is as follows:

 DATA data1;
SET data0;
BY ID YEAR ;
IF LAST.ID THEN END = _N_;
IF Var1 > 0 THEN CNT=_N_;
RUN;
DATA data2;
SET data1;
BY ID YEAR ;
Var2 = 0;
IF Var1 = 1 THEN DO;
    DO I = CNT TO END;
        Var[I] = 1; 
    END;
END;
RUN;

However, SAS does not loop along observations.


Solution

  • I'm not sure what your example is doing, but this is fairly straightforward.

    data want;
      set have;
      by id;
      retain var2;
      if first.id then var2=0;
      if var1=1 then var2=1;
    run;
    

    Retain var2 to keep its value across observations, and then set it to 1 when you see a 1 in var1; finally, set it to 0 when you see a first.id row.