DATA Step, Macro, Functions and more

Concatenating Strings

Accepted Solution Solved
Reply
Contributor
Posts: 41
Accepted Solution

Concatenating Strings

[ Edited ]

I am trying to take a list of text items associated with key values and concatenate them into semicolon-delimited lists.  Instead, I'm getting lists of semicolons only.  I can't figure out what is going wrong.  This is SAS 9.4 for Windows.

 

 

ODS HTML;
DATA HAVE;
     INPUT Key $ 1 Text $ 3-20;
     CARDS;
A Alpha One
A alpha two
A Alpha 3
B bee one
C See me
C See you
;;;
RUN;

PROC SORT DATA=Have;
     by Key;
run;

PROC PRINT;
     TITLE Have;
RUN;

DATA NotWhatIWant (KEEP=Key List);
     SET HAVE;
     BY Key;
     LENGTH List $50;
     RETAIN LIST;
     IF first.key THEN
          LIST = ' ';
     LIST = CATX(List,';',Text);
     IF LAST.KEY THEN
          OUTPUT NotWhatIWant;
RUN;

PROC PRINT DATA=NotWhatIWant;
     TITLE Not What I Want;
RUN;
ODS CLOSE;

what I want.PNG

 

 

 

 

 

 

not what I want.PNG

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Accepted Solutions
Solution
3 weeks ago
Super User
Super User
Posts: 7,997

Re: Concatenating Strings

You were nearly there, I update your code.  Do avoid coding all in uppercase or mixed case, its really hard to read.

proc sort data=have;
  by key;
run;

data notwhatiwant (keep=key list);
  set have;
  by key;
  length list $50;
  retain list;
  list=ifc(first.key,'',catx(';',list,text));
  if last.key;
run;

Note how I use ifc() boolean function to simplfy the if, and you do not need the output notwhatiwant.  

View solution in original post


All Replies
Super User
Posts: 5,441

Re: Concatenating Strings

Are your sure that HAVE is looking good?
Use put statements or the data step debugger to analyze your variables during execution.
Data never sleeps
Super User
Posts: 5,518

Re: Concatenating Strings

When using CATX, the first parameter (not the second) should be the delimiter. 

Solution
3 weeks ago
Super User
Super User
Posts: 7,997

Re: Concatenating Strings

You were nearly there, I update your code.  Do avoid coding all in uppercase or mixed case, its really hard to read.

proc sort data=have;
  by key;
run;

data notwhatiwant (keep=key list);
  set have;
  by key;
  length list $50;
  retain list;
  list=ifc(first.key,'',catx(';',list,text));
  if last.key;
run;

Note how I use ifc() boolean function to simplfy the if, and you do not need the output notwhatiwant.  

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 161 views
  • 5 likes
  • 4 in conversation