How to populate the string in reverse order. For example I have a variable under name
Fname |
Praveen Kumar |
Gowtham Kuppal KK |
Hari Haran M |
I want the output to be in the required format:
Fname |
Kumar Praveen |
KK Kuppal Gowtham |
M Haran Hari |
Thanks in Advance
One way
data have;
input Fname $50.;
datalines;
Praveen Kumar
Gowtham Kuppal KK
Hari Haran M
;
data want;
set have;
length FnameNew $ 50;
do _N_ = countw(Fname) to 1 by -1;
FnameNew = catx(' ', FnameNew, scan(Fname, _N_));
end;
run;
Result:
Fname FnameNew Praveen Kumar Kumar Praveen Gowtham Kuppal KK KK Kuppal Gowtham Hari Haran M M Haran Hari
What should happen if the name consists of four words?
I would recommend @PeterClemmensen's solution over the code in this post as it works with any number of names (see question from @andreas_lds).
When I saw "reverse" in the title I just thought how might the reverse() function be used, so just for demonstration purposes, the following produces the required result for the input data provided:
data want;
set have;
length name2 $ 50;
name2 = reverse(catx(' '
,reverse(scan(fname,1))
,reverse(scan(fname,2))
,reverse(scan(fname,3))
));
run;
Kind regards,
Amir.
You can place the fname word parts, reversely indexed in a loop, in an array (i.e. conceptually a 'reverse/split') and perform a single CATX after the loop.
Example:
data have; input Fname $50.; datalines; Praveen Kumar Gowtham Kuppal KK Hari Haran M ; data want; set have; array items(0:49) $50 _temporary_; do _n_ = 1 to countw(fname); items(dim(items)-_n_) = scan(fname, _n_); end; fname = catx(' ', of items(*)); run;
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.