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

Hello--

 

I recently received a data set with Var1 values: '1'  '2'  '3'  '4'  '5'  '10'  '11'  '12'  '13'  '14'  '15'  'unknown.'  This variable is obviously character, but I need leading 0s on the digits that are less than 10. Is there an elegant way to do this?

 

Thanks 

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

Hello @raivester,

 

I'd suggest this:

data want;
set have;
if lengthn(var1)=1 then var1='0'||var1;
run;

(I use LENGTHN, not LENGTH, because missing values should not be replaced by zeros.)

View solution in original post

7 REPLIES 7
Reeza
Super User
Want = put(input(var1, 8.), z2.);

Or convert it to a number and display with Z2 format.

want = input(var1, 8.);
format want Z2.;
raivester
Quartz | Level 8

will this work if one of the variable values is the character string "unknown"?

Reeza
Super User
No, but you could add an IF to conditionally execute the conversion or change unknown to show as missing or a SAS special missing value.
Kurt_Bremser
Super User

Try this:

data have;
input var1 $;
datalines;
1
2
3
4
5
6
11
12
13
14
15
unknown
;

data want;
set have;
if anyalpha(var1) = 0
then var1 = put(input(var1,best.),z2. -l);
run;
FreelanceReinh
Jade | Level 19

Hello @raivester,

 

I'd suggest this:

data want;
set have;
if lengthn(var1)=1 then var1='0'||var1;
run;

(I use LENGTHN, not LENGTH, because missing values should not be replaced by zeros.)

raivester
Quartz | Level 8

Ahh! Good thinking. Thanks for the help

ballardw
Super User

Do you expect to need to do arithmetic with these values? Or model with the numeric value ?

If so, then read them as numeric so the unknown are missing and if you need a leading zero use a Z2. format.

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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
  • 7 replies
  • 1509 views
  • 3 likes
  • 5 in conversation