Search code examples
sassas-macro

SAS Vlookup in the same table


my case is finding value in this same table (for Variable2 from Value). Can you help me? I need a SAS code for this case.

enter image description here

I tried to solve this way:

data example2;                                                 
 input Variable Value Variable2;                                                  
    datalines;                                                    
    V1 3 V2 
    V2 6 V1 
    V3 4 V5 
    V4 1 V1 
    V5 5 V2 
    ;

    proc sort data=example2;
        by Variable;
    run;
    data example19;
      set example2;
      merge example2 example2 (keep=Value Variable2 rename=(Value=new));                             
    run;  

Solution

  • below code should work for your scenario. I have checked for couple of edge case scenarios and it works as expected. Just check once again if it fails any edge case other this

     data have;
      input variable $ value variable2 $;
      datalines;
      V1 3 V2
      V2 6 V1
      V3 4 V5
      V4 1 V1
      V5 5 V2
     ;
    
    
       proc sql;
      create table want as 
         select  a.variable ,a.value, a.variable2 ,   b.value as value2            
      from have a
      left join
      have b
      on  a.variable2 =b.variable
      order by variable;
    
    proc sql;
     select * from want;
    
    /* once edge case scenario where you do not have variable for variable2 it 
      works as expected giving a null value*/
    
    data have1;
     input variable $ value variable2 $;
    datalines;
    V1 3 V2
    V2 6 V1
     V3 4 V5
    V4 1 V1
    V5 5 V2
    V9 8 V7
     ;