Hi guys,
I am trying to concatenate two variables(var1 and var2) . Can anyone suggest me how this can be done
var1 var2 Var3
Q1 Q3 Q1,Q3
The final output should be like var3.
Thaks in advance
Fortunately it's the simplest thing in the world. Well, not the simplest thing. But still fairly simple.
data _null_;
var1 = 'Q1';
var2 = 'Q3';
length var3 $ 5;
var3 = catx(',', var1, var2);
put _all_;
run;
catx takes as its first parameter the separator you want, followed by the variables (and there can be many more) you want to concatenate.
It's magic!
(Editor's note: see more details in How to concatenate values in SAS.)
Fortunately it's the simplest thing in the world. Well, not the simplest thing. But still fairly simple.
data _null_;
var1 = 'Q1';
var2 = 'Q3';
length var3 $ 5;
var3 = catx(',', var1, var2);
put _all_;
run;
catx takes as its first parameter the separator you want, followed by the variables (and there can be many more) you want to concatenate.
It's magic!
(Editor's note: see more details in How to concatenate values in SAS.)
As a minor clarification to @LaurieF's fine solution, the LENGTH of the new variable is important and needs to be set to the sum of the lengths of the longest values of Var1 and Var2 plus 1 for the comma. Otherwise you may experience truncation of your values. Note that CATX may tell that you need a longer variable with a message.
data _null_; var1 = 'Q123'; var2 = 'Q345'; length var3 $ 8; var3 = catx(',', var1, var2); put _all_; run;
Will generate:
WARNING: In a call to the CATX function, the buffer allocated for the result was not long enough to contain the concatenation of all the arguments. The correct result would contain 9 characters, but the actual result may either be truncated to 8 character(s) or be completely blank, depending on the calling environment. The following note indicates the left-most argument that caused truncation.
which tells the minimum length you should set for VAR3
Like this? 🙂
data have;
input var1 $ var2 $;
datalines;
Q1 Q3
;
data want;
set have;
var3 = catx(',', var1, var2);
run;
Same solution as @LaurieF
I beat @PeterClemmensen by seconds, i think!
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.