BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
vxhong17
Calcite | Level 5

I want to convert a character variable (stub) to a new variable (stub1). Rules are that the first 5 or 6 characters before m or e are kept (e.g, B01001e1 -> keep B01001 and B01001Ee -> keep B01001E) and that numbers after m or e are added to three digits (e.g. 1 -> 001, 12 -> 012, 123 -> 123).

For example,

B01001e1 -> B01001001

B02001m12 = B02001012

B01001Ee1 -> B01001E001

B05003Fm123 -> B05003F123

How can I deal with this matter?  Thank you so much

1 ACCEPTED SOLUTION

Accepted Solutions
Haikuo
Onyx | Level 15

I knew it. Smiley Happy. Here is another variation:

data want;

  set have;

  substr(var,length(scan(var,1,'me'))+1)=put(input(scan(var,2,'me'),best.),z3.);

  run;

Haikuo

View solution in original post

5 REPLIES 5
Reeza
Super User

You can look at some string functions such as compress using e/m as delimiters as well as translate to do the conversion for the other characters, or a format that does the conversion for the second part would also work.

Haikuo
Onyx | Level 15

This is to follow Fareeza's logic. I am sure there would be better code than the following:

data have;

input var $20.;

cards;

B01001e1

B02001m12

B01001Ee1

B05003Fm123

;

data want;

  set have;

  _l=length(scan(var,1,'me'));

  newvar=cats(substr(var,1,_l+1),put(input(substr(var,_l+2),best.),z3.));

  drop _l;

  run;

Haikuo

data_null__
Jade | Level 19

same but different.

17         data _null_;
18            input var $20.;
19            i = findc(var,'me');
20            substr(var,i)=put(input(substr(var,i+1),3.),z3.);
21            put (_all_)(=);
22            cards;

var=B01001001 i=
7
var=B02001012 i=
7
var=B01001E001 i=
8
var=B05003F123 i=
8
Haikuo
Onyx | Level 15

I knew it. Smiley Happy. Here is another variation:

data want;

  set have;

  substr(var,length(scan(var,1,'me'))+1)=put(input(scan(var,2,'me'),best.),z3.);

  run;

Haikuo

vxhong17
Calcite | Level 5

Hi data_null_, Reeza,

Thank you so much for your help,

Hi Hai.kuo,

Thank you so much for your nice sample code.

Best Regards,

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

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
  • 5 replies
  • 489 views
  • 6 likes
  • 4 in conversation