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.

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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