6
votes

I wonder whether it's possible to concatenate each record within one observation with SAS code. E.g.

Here is the original data set

1st_name 2nd_name 3rd_name .....last_name

   abc   def      ghi .....     xyz

Now I want to add a variable that concatenates all values from 1st_name to last_name--separated by a specific separator, if possible.

Expected result

1st_name 2nd_name 3rd_name .....last_name   all_name

   abc   def      ghi .....     xyz     abcdefg...xyz 

Of course there is one way

data name;
  set name;
  length all_name $ 30;
  all_name=1st_name||2nd_name....||last_name;
run;

However, things will get terrible if there are hundreds of variables. So the question has been how to do it automatically, without having to specify variable names, numbers etc.

Looking forward to answers from SAS experts:)

2

2 Answers

8
votes

The code below should work. You'll need to tweak it to your own situation. What it does is creating an array of all character variables. If the name contains the value name it will be concatenated. The catx functions trims the values and uses the first parameter as seperator. Just be aware that the maximum size of a SAS field is 32767 characters, so concatenating hundreds of variables might result in an error.

data concatnames (drop=i);
 * maximum field length, will contain concatenated names;
 attrib all length=$32767.;
 * read source dataset;
 set names;
 * create array with with character fields;
 array char_array {*} _character_;
 * loop through array;
 do i = 1 to dim(char_array);
  * if fieldname contains name, then add to all with a dash as seperator;
  if (index(vname(char_array{i}),"name") ne 0) then all = catx("-",all,char_array{i});
 end;
run;
7
votes

If the variables to concatenate are in order, your can use the "of" syntax with a variable list (the double dash) to simplify the code.

data name;
  length all_name $32767.;
  set name;
  allname=cats(of first_name--last_name);
run;