Search code examples
arraysmacrossasretain

Filling missing values for many variables from previous observation by group in SAS


My dataset looks like this:

Date  ID Var1 Var2 ... Var5
200701 1  x    .    
200702 1  .    a
200703 1  .    .
200701 2  .    b 
200702 2  y    b
200703 2  y    .
200702 3  z    .
200703 3  .    .

I want my results to look like this:

Date  ID Var1 Var2 ... Var5
200701 1  x    .
200702 1  x    a
200703 1  x    a
200701 2  .    b 
200702 2  y    b
200703 2  y    b
200702 3  z    .
200703 3  z    .

I tried the following code below, but it didn't work. What's wrong with it? Am I better off using array? If so, how?

%macro a(variable);
length _&variable $10.;
retain _&variable;
if first.ID then _&variable = '';
if &variable ne '' then _&variable=&variable;
else if &variable = '' then &variable=_&variable;
drop _&variable;
%mend;

data want;
set have;
%a(Var1)
%a(Var2)
%a(Var3)
%a(Var4)
%a(Var5)
run;

Appreciate the help! Thanks!


Solution

  • The full code works! Thanks

    %macro a(variable);
    length _&variable $10.;
    retain _&variable;
    if first.ID then _&variable = '';
    if &variable ne '' then _&variable=&variable;
    else if &variable = '' then &variable=_&variable;
    drop _&variable;
    %mend;
    
    data want;
    update have(obs=0) have;
    by id;
    output;
    %a(Var1)
    %a(Var2)
    %a(Var3)
    %a(Var4)
    %a(Var5)
    run;