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.
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;
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;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.