I have a dataset that looks like this:
obs ID1 ID2 ID3
1 X Y Z
2 A B C
3 D D E
4 M N N
etc.
I'd like to produce a new variable that counts the number of unique strings across the ID variables. So it would produce this:
obs ID1 ID2 ID3 Count
1 X Y Z 3
2 A B C 3
3 D D E 2
4 M N N 2
Suggestions?
1. Sort the array
2. Loop over array and check if it matches the previous value.
If you don't want to sort your data you can copy the array to another temporary array and drop it.
data have;
input obs ID1 $ ID2 $ ID3 $;
cards;
1 X Y Z
2 A B C
3 D D E
4 M N N
;
run;
data want;
set have;
array _id(3) id1-id3;
call sortc(of _id(*));
count=1;
do i=2 to dim(_id);
if _id(i) ne _id(i-1) then count+1;
end;
run;
Another solution is to transpose your data to a long format and use PROC SQL with COUNT DISTINCT or a double PROC FREQ.
An example of that is here:
https://github.com/statgeek/SAS-Tutorials/blob/master/count_distinct_by_group
1. Sort the array
2. Loop over array and check if it matches the previous value.
If you don't want to sort your data you can copy the array to another temporary array and drop it.
data have;
input obs ID1 $ ID2 $ ID3 $;
cards;
1 X Y Z
2 A B C
3 D D E
4 M N N
;
run;
data want;
set have;
array _id(3) id1-id3;
call sortc(of _id(*));
count=1;
do i=2 to dim(_id);
if _id(i) ne _id(i-1) then count+1;
end;
run;
Another solution is to transpose your data to a long format and use PROC SQL with COUNT DISTINCT or a double PROC FREQ.
An example of that is here:
https://github.com/statgeek/SAS-Tutorials/blob/master/count_distinct_by_group
thank you! this helps because I wanted to also create some flags based on the uniqueness conditions. these will be easy to add to this set up.
It is very easy for IML code due to the function COUNTUNIQUE(). Or Hash Table can do it though. data have; input obs (ID1 ID2 ID3) ($); cards; 1 X Y Z 2 A B C 3 D D E 4 M N N ; run; data want; if _n_=1 then do; length k $ 200; declare hash h(); h.definekey('k'); h.definedone(); end; set have; array x{*} $ id1-id3; do i=1 to dim(x); if not missing(x{i}) then do;k=x{i};h.ref();end; end; count=h.num_items; h.clear(); drop i; run;
Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.
Register today!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.
Select SAS Training centers are offering in-person courses. View upcoming courses for: