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

data have;

     input x $;

     cards;

     24

     1

     3mn8

     s27

     25

;run;

Now I have to create a variable y of length=6, such as:

000024

000001

003mn8

0000s27

000025

How can I do this? Any help appreciated!

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User

WOW, so many brilliant solutions , Just want to add another solution. Smiley Wink

data have;
  input x : $4.;
  cards;
  24
  1
  3mn8
  s27
  25
;
run;
data want;
 length x $ 6;
 set have;
 xx=translate(right(x),'0',' ');
run;

Ksharp

View solution in original post

6 REPLIES 6
Astounding
PROC Star

y = '000000';

substr(y, 7-length(x)) = x;

But there better not be any blank values for X, or any longer than 6 characters.

Good luck.

Linlin
Lapis Lazuli | Level 10

data have;
     input x $;
     cards;
     24
     1
     3mn8
     s27
     25
;
data want;
set have;
do _n_=1 to 6-length(x);
x=cats('0',x);
end;
run;
proc print;run;
                                             Obs      x

                                             1     000024
                                             2     000001
                                             3     003mn8
                                             4     000s27
                                             5     000025

Haikuo
Onyx | Level 15

Or this:

data have;

  input x $;

  cards;

  24

  1

  3mn8

  s27

  25

;

data want;

set have;

x=repeat('0',6-length(x))||left(x);

run;

proc print;run;

Regards,

Haikuo

Astounding
PROC Star

There's a pitfall using REPEAT.  It starts with your first parameter, then repeats it an ADDITIONAL number of times.  You will get one more zero than you bargained for!

Haikuo
Onyx | Level 15

Aha! Good catch! I did NOT know that. And I am sorry I did not count it either.

I guess OP should know how to modify my code to overcome this pitfall. Smiley Happy

Haikuo

Ksharp
Super User

WOW, so many brilliant solutions , Just want to add another solution. Smiley Wink

data have;
  input x : $4.;
  cards;
  24
  1
  3mn8
  s27
  25
;
run;
data want;
 length x $ 6;
 set have;
 xx=translate(right(x),'0',' ');
run;

Ksharp

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