I have a dataset with 2000 observations. It contains ID, var1, var2.
Var1="11,21,43,35" or "11" or any combination of these numbers. sometimes just one number, sometimes two numbers.
Var2="20,21,35,43" or or any combination of these numbers. sometimes just one number, sometimes two numbers.
I would like to generate a new variable to find any overlap or matching numbers between these two variables.
For example, when var1="11,21,43,25" and var2="20,21,35,43" then matching="21";
when var1="11" and var2="35" then matching=.;
when var1="11,21,35" and var2="21,35,43" then matching="21,35".
Data want;
input ID var1 $ var2 $;
datalines;
1 11,21,43,35 11
2 11,21,43,25 20,21,35,43
3 11 35
4 11,21,35 21,35
5 21 35,21,43
;
Any suggestions would be greatly appreciated.
Data have;
input ID var1 :$12. var2 :$12.;
datalines;
1 11,21,43,35 11
2 11,21,43,25 20,21,35,43
3 11 35
4 11,21,35 21,35
5 21 35,21,43
;
data want;
set have;
nvar1=countw(var1,',');
nvar2=countw(var2,',');
length match $ 30;
match=' ';
do i=1 to nvar1;
do j=1 to nvar2;
if scan(var1,i,',')=scan(var2,j,',') then match=catx(',',match,scan(var1,i,','));
end;
end;
drop i j nvar:;
run;
Data have;
input ID var1 :$12. var2 :$12.;
datalines;
1 11,21,43,35 11
2 11,21,43,25 20,21,35,43
3 11 35
4 11,21,35 21,35
5 21 35,21,43
;
data want;
set have;
nvar1=countw(var1,',');
nvar2=countw(var2,',');
length match $ 30;
match=' ';
do i=1 to nvar1;
do j=1 to nvar2;
if scan(var1,i,',')=scan(var2,j,',') then match=catx(',',match,scan(var1,i,','));
end;
end;
drop i j nvar:;
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and save with the early bird rate—just $795!
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.
Ready to level-up your skills? Choose your own adventure.