DATA Step, Macro, Functions and more

Reanaming observations

Reply
Frequent Contributor
Posts: 114

Reanaming observations

HI SAS Experts,

 

I am tryng to replace a group of words of an observations with its starting letter, is there is anyway to do this. Please help

 

Sample dataset.


data a;
input name$;
cards;
name_ks_a_dfdfdf
name_ks_a_hjhj
name_class__hhjghjh
name_class___jnjjjk
name_marks_ghgjk
name_marks_ghjkjk
;run;

 

 

output:

name1
n_k_a_dfdfdf
n_k_a_hjhj
n_c_hhjghjh
n_c_jnjjjk
n_m_ghgjk
n_m_ghjkjk

 

Best Regards,

Sanjay

PROC Star
Posts: 551

Re: Reanaming observations

You want to replace strings of text separated by _ by their starting letter, but not the last part, correct?

Frequent Contributor
Posts: 114

Re: Reanaming observations

yes Exactly

Frequent Contributor
Posts: 114

Re: Reanaming observations

Yes Exactly
Super User
Super User
Posts: 7,395

Re: Reanaming observations

Weird request.  Sounds like your process is broken before this.  You can do it:

data a;
  length name $200;
  input name $;
cards;
name_ks_a_dfdfdf
name_ks_a_hjhj
name_class__hhjghjh
name_class___jnjjjk
name_marks_ghgjk
name_marks_ghjkjk
;
run;
data want;
  set a;
  length new_name $200;
  new_name=catx("_","n",char(scan(name,2,"_"),1),reverse(scan(reverse(name),1,"_")));
run;
Super User
Posts: 5,080

Re: Reanaming observations

[ Edited ]

One way:

 

data want;

set have;

length new_name $ 100 letter $ 1;

n_words = countw(name, '_');

if n_words <= 1 then return;

do i=1 to n_words - 1;

   letter = scan(name, i, '_');

   new_name = catx('_', new_name, letter);

end;

new_name = catx('_', new_name, scan(name, -1, '_'));

drop letter;

run;

Ask a Question
Discussion stats
  • 5 replies
  • 105 views
  • 0 likes
  • 4 in conversation