BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Stu_J
Calcite | Level 5

hello,

I would like to get only the distinct values for a new variable.

for example,

ID var

1 AABI

2 TIBBC

3 TTIBTIC

so I would like to have a the new variable as output below:

ID var var_new

1 AABI ABI

2 TIBBC TIBC

3 TTIBTIC TIBC

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

data have;
input ID var $;
cards;
1 AABI
2 TIBBC
3 TTIBTIC
;

data want ;
 if _n_=1 then do;
   dcl hash H () ;
   h.definekey  ("k") ;
   h.definedone () ;
 end;
 set have;
 length var_new $30;
 do _n_=1 to lengthn(var);
  k= char(var,_n_);
  if h.check()=0 then continue;
  var_new=cats(var_new,k);
  h.add();
 end;
 h.clear();
 drop k;
run;

View solution in original post

5 REPLIES 5
mkeintz
PROC Star

What about ABAI?  I has 2 A's, but they are not contiguous.

--------------------------
The hash OUTPUT method will overwrite a SAS data set, but not append. That can be costly. Consider voting for Add a HASH object method which would append a hash object to an existing SAS data set

Would enabling PROC SORT to simultaneously output multiple datasets be useful? Then vote for
Allow PROC SORT to output multiple datasets

--------------------------
Stu_J
Calcite | Level 5
Only keeping the distinct values, so ABAI new variable will be ABI
novinosrin
Tourmaline | Level 20

data have;
input ID var $;
cards;
1 AABI
2 TIBBC
3 TTIBTIC
;

data want ;
 if _n_=1 then do;
   dcl hash H () ;
   h.definekey  ("k") ;
   h.definedone () ;
 end;
 set have;
 length var_new $30;
 do _n_=1 to lengthn(var);
  k= char(var,_n_);
  if h.check()=0 then continue;
  var_new=cats(var_new,k);
  h.add();
 end;
 h.clear();
 drop k;
run;
Stu_J
Calcite | Level 5

thanks, I don't have much knowledge with hash object. that's very nice.

Ksharp
Super User

data have;
input ID var $;
cards;
1 AABI
2 TIBBC
3 TTIBTIC
;
data want;
 set have;
 array x{100} $ 1 _temporary_;
 n=0;call missing(of x{*});
 do i=1 to length(var);
   temp=char(var,i);
   if temp not in x then do;n+1;x{n}=temp;end;
 end;
 want=cats(of x{*});
 drop n i temp;
run;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 874 views
  • 2 likes
  • 4 in conversation