BookmarkSubscribeRSS Feed
Aayushi_17
Quartz | Level 8

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

4 REPLIES 4
PeterClemmensen
Tourmaline | Level 20

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 
andreas_lds
Jade | Level 19

What should happen if the name consists of four words?

Amir
PROC Star

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.

RichardDeVen
Barite | Level 11

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-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 824 views
  • 4 likes
  • 5 in conversation