BookmarkSubscribeRSS Feed
sanjay1
Obsidian | Level 7

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

5 REPLIES 5
PeterClemmensen
Tourmaline | Level 20

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

sanjay1
Obsidian | Level 7

yes Exactly

sanjay1
Obsidian | Level 7
Yes Exactly
RW9
Diamond | Level 26 RW9
Diamond | Level 26

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;
Astounding
PROC Star

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;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 1080 views
  • 0 likes
  • 4 in conversation