Would it be possible to reorder a list of comma separated values stored as a variable string? The string could have any number of comma separated values or it could have just one value with no comma in some cases.
For example a character variable stored with the value of:
'12345, 54321, 23456, 65432'
Could it be reordered numerically (or alphabetically if it includes alphabetic characters) to appear as:
'12345, 23456, 54321, 65432'
Any suggestions would very helpful. Thanks.
Something like this?
data _null_;
length string $100;
string='12345, 54321, 23456, 65432';
array num{4} $;
do i=1 to dim(num);
num[i]=scan(string, i);
end;
call sortc(of num[*]);
newstring=catx(', ', of num[*]);
put string= // newstring=;
run;
Something like this?
data _null_;
length string $100;
string='12345, 54321, 23456, 65432';
array num{4} $;
do i=1 to dim(num);
num[i]=scan(string, i);
end;
call sortc(of num[*]);
newstring=catx(', ', of num[*]);
put string= // newstring=;
run;
No problem, glad to help 🙂
An alternative approach, where you do not have to specify the number of entries (4) beforehand
data _null_;
declare hash h(ordered:"Y");
h.definekey('num');
h.definedone();
declare hiter hi('h');
length string $100 newstring $100;
string='12345, 54321, 23456, 65432';
do i=1 to countw(string, ',');
num=scan(string, i, ', ');
h.add();
end;
do while (hi.next()=0);
newstring=catx(', ', newstring, num);
end;
put string // newstring;
run;
Are the strings always 5 bytes of chars in length as your example ?
In the numeric case, you can alter the hash object code as
data _null_;
declare hash h(ordered:"Y");
h.definekey('num');
h.definedone();
declare hiter hi('h');
length string $100 newstring $100;
string='12345, 123456, 54321, 23456, 65432';
do i=1 to countw(string, ',');
num=input(scan(string, i, ', '), 8.);
h.add();
end;
do while (hi.next()=0);
newstring=catx(', ', newstring, num);
end;
put string // newstring;
run;
Ok. I think i would stick to arrays and not hash. You can initiallise the subscript as high as you want. Catx anyways strips of the leading and trailing blanks. Also, you don't have to loop through te string to split once and then loop through the hasn contents. Two sets of loops are not needed i think.
Also Hash contents has to be cleared for every iteration
h.clear();
A lot of overhead after all.
Plus temporary arrays are much faster although a call missing would be needed. So for this scenario, i personally would go for temp arrays
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.