DATA Step, Macro, Functions and more

Creating subset of data by matching multiple variables to second data set using

Reply
Super Contributor
Posts: 312

Creating subset of data by matching multiple variables to second data set using

I have data A and B:

data A;
input ID  visit  accessor_ID SPID  score1 score2 score3 ;
datalines;
1 1 1 1 79 70 80
1 1 2 1 89 81 86
1 2 1 1 74 79 82
1 2 2 1 69 75 81
;
run;

data B;
input ID  visit  accessor_ID SPID  score1 score2 score3 ;
datalines;
1 1 1 1 73 75 70
1 1 1 2 81 82 90
1 1 2 1 89 81 86
1 1 2 2 79 84 88
1 2 1 1 74 79 82
1 2 1 2 86 76 77
1 2 2 1 69 75 81
1 2 2 2 78 75 83
;
run;

I want to subset data B, only keep obs which have the matching first four varibles in set A:

/* want to subset data B, to only keep those with matching (ID visit accessor_ID spid), i.e.
1 1 1 1 73 75 70
1 1 2 1 89 81 86
1 2 1 1 74 79 82
1 2 2 1 69 75 81 
*/

proc sort data=A out=unique_set (keep=ID visit accessor_ID spid); by ID visit accessor_ID spid; run;
proc sort data=B; by ID visit accessor_ID spid; run;
data B_subset;
merge B (in=a) unique_set (in=b);
by ID visit accessor_ID spid; 
if A and B;
run;

The above code works, but I wonder if there are other methods (like using proc sql etc). Thanks. 

 

Valued Guide
Posts: 797

Re: Creating subset of data by matching multiple variables to second data set using

Matching multiple variables:  hash is probably the most robust method.  No sorting required.

 

data want (drop=rc);

  if _n_=1then do;

    if 0 then set a (keep=ID  visit  accessor_ID SPID  );

    declare hash lookupa (dataset:'A (keep=id visit accessor_id spid)');

      lookupa.definekey(all:'Y');

      lookupa.definedone():

  end;

  set b;

  rc=lookupa.find();

  if rc=0;

run;

Super User
Posts: 10,483

Re: Creating subset of data by matching multiple variables to second data set using

One way that MAY work if your two comparison sets do not have as many matches for variables ID visit accessor_ID SPID score1 would be:

proc sql ;
   create table b_subset as
   select b.*
   from b natural join a;
quit; 

Natural join actually looks at your data and guesses how to link records. In your example data case you have many matches including the SCORE1 value so that gets used and only returns the 3 records that match on 5 varibles. No sort is needed.

 

 

Another option would be to specify the variables that must match:

 

proc sql ;
   create table b_subset as
   select b.*
   from a  join b on
     a.id=b.id and a.visit=b.visit and a.accessor_ID=b.accessor_ID and a.spid=b.spid;
quit; 
Ask a Question
Discussion stats
  • 2 replies
  • 106 views
  • 0 likes
  • 3 in conversation