Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concatenate each record within one observation in SAS

Tags:

sas

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:)

like image 853
mj023119 Avatar asked Mar 25 '11 06:03

mj023119


1 Answers

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;
like image 52
Laurent de Walick Avatar answered Sep 27 '22 23:09

Laurent de Walick