Character variable

Accepted Solution Solved
Reply
Contributor
Posts: 51
Accepted Solution

Character variable

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


Accepted Solutions
Solution
‎05-21-2013 08:21 PM
Respected Advisor
Posts: 3,156

Re: Character variable

Posted in reply to data_null__

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


All Replies
Super User
Posts: 19,770

Re: Character variable

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.

Respected Advisor
Posts: 3,156

Re: Character variable

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

Respected Advisor
Posts: 3,799

Re: Character variable

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
Solution
‎05-21-2013 08:21 PM
Respected Advisor
Posts: 3,156

Re: Character variable

Posted in reply to data_null__

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

Contributor
Posts: 51

Re: Character variable

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,

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 206 views
  • 6 likes
  • 4 in conversation