Q: Replace string with previous/forward other string in SAS I have a dataset which contains -1, which is the same as missing which I would like to replace with firstly previously known, and that is not found with forward known. By group V1 and V2
Example:
data test;
    input V1 $ V2 $ V3 $;
    infile datalines delimiter=',';
datalines;
A,X,AA0
A,X,-1
A,X,AA0
A,Y,-1
A,Y,BB2
B,X,-1
B,X,-1
B,X,CC1
B,Y,-1
B,Y,-1
;

After first run (filling down)
   V1    V2    V3   
 1 A     X     AA0  
 2 A     X     AA0  
 3 A     X     AA0  
 4 A     Y     -1
 5 A     Y     BB2  
 6 B     X     -1   
 7 B     X     -1
 8 B     X     CC1  
 9 B     Y     -1
10 B     Y     -1

After second run (filling up):
   V1    V2    V3   
 1 A     X     AA0  
 2 A     X     AA0  
 3 A     X     AA0  
 4 A     Y     BB2  
 5 A     Y     BB2  
 6 B     X     CC1  
 7 B     X     CC1  
 8 B     X     CC1  
 9 B     Y     NA   
10 B     Y     NA 

I found there is a similar question here
However, I dont get the desired result when replacing '.' for '-1' and the replaced values, for example AA0 becomes AA. 
This is my try:
proc sort data=test;
  by V1
     V2;
run;
data want;
  set test;
  by V1 V2;
  retain new_var ('-1');

  if not last.V1 and V3 ne '-1' then new_var=V3;
  else if V3 = '-1' then V3 = new_var;
  if last.V1 then new_var = '-1';

   /* drop year_tmp; */
run;


A: Use a DOW loop to find the first forward non-missing V3 value, followed by a second loop over group using different SET buffer to track most recent prior V3 value in group and fill in either needed forward V3 or prior V3.  The code performs fill-in with a precedence of prior over first.
data want;
  length firstv3 priorv3 $8;

  do _n_ = 1 by 1 until (last.v2);
    set test;
    by v1 v2;
    if missing(firstv3) and v3 ne '-1' then firstv3 = v3;
  end;

  do _n_ = 1 to _n_;
    set test;

    if v3 ne '-1' then
      priorv3 = v3;
    else do;
      if not missing(priorv3) then v3 = priorv3;
      else
      if not missing(firstv3) then v3 = firstv3;
    end;

    output; 
  end;
run;

