Not applicable
Posts: 0

# separating a string of digits

Hi,

what is the way to separate a string of digits (e.g. 1103) in 3 different column? I have a string of 4 digits. the first digit symbolize "attribute 1" the second "attribute 2" the last two the IDnumber.

Thanks!
Super Contributor
Posts: 359

## Re: separating a string of digits

var1 = substr(str, 1,1);
var2 = substr(str, 2,1);
var3 = substr(str, 3,2);
Super Contributor
Posts: 3,176

## Re: separating a string of digits

In a DATA step, use the SUBSTR function to parse your data in SAS variable assignment statements.

SAS functions are documented here:

http://support.sas.com/documentation/cdl/en/lrdict/62618/HTML/default/a000245852.htm

Scott Barry
SBBWorks, Inc. Message was edited by: sbb
Not applicable
Posts: 0

## Re: separating a string of digits

thank you.

This works, but only when I import the data as character.

When I have Numeric like;

Data a;
data a;
set a;
str=1103
var1 = substr(str, 1,1);
var2 = substr(str, 2,1);
var3 = substr(str, 3,2);
RUN;

it doesn't work.

When I have used the digits as characters, then I can not convert it back in numeric. The procedure
informat var1 var2 best1. var3 best2.;
format var1 var2 best1. var3 best2.;
can't be interpret by sas.

Thanks.
Super Contributor
Posts: 339

## Re: separating a string of digits

Hi Lex,

If you'll need to convert it back in numeric you might want to use the input function. And just a curious about this, why convert it back to numeric after you have changed it into a character already? Will you be using the splitted digits for computations?

Regards,
Milton
Super Contributor
Posts: 3,176

## Re: separating a string of digits

In order to parse a SAS numeric variable based on digit-position, you must use the SAS PUT function with the desired output FORMAT (second argument), such as Z4., in order to give you a formatted SAS variable/value to parse.

Scott Barry
SBBWorks, Inc.
Posts: 3,852

## Re: separating a string of digits

The easy way is to [pre]substr(put(x,z4.)...[/pre] but you can do it with arithmitic functions.

[pre]
350 data _null_;
351 do s = 1103,1010,0330,0901,0001,9999,0000;
352 a = int(s/1e3);
353 b = int(mod(int(s/1e2),1e1));
354 c = int((s/1e2-int(s/1e2))*1e2);
355 put (_all_)(=);
356 end;
357 format s z4. a b f1. c z2.;
358 run;

s=1103 a=1 b=1 c=03
s=1010 a=1 b=0 c=10
s=0330 a=0 b=3 c=30
s=0901 a=0 b=9 c=01
s=0001 a=0 b=0 c=01
s=9999 a=9 b=9 c=99
s=0000 a=0 b=0 c=00
[/pre]
Discussion stats
• 6 replies
• 165 views
• 0 likes
• 5 in conversation