Help using Base SAS procedures

separating a string of digits

Reply
N/A
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

Posted in reply to deleted_user
var1 = substr(str, 1,1);
var2 = substr(str, 2,1);
var3 = substr(str, 3,2);
Super Contributor
Super Contributor
Posts: 3,174

Re: separating a string of digits

Posted in reply to deleted_user
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
N/A
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: 326

Re: separating a string of digits

Posted in reply to deleted_user
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
Super Contributor
Posts: 3,174

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.
Respected Advisor
Posts: 3,799

Re: separating a string of digits

Posted in reply to deleted_user
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]
Ask a Question
Discussion stats
  • 6 replies
  • 149 views
  • 0 likes
  • 5 in conversation