DATA Step, Macro, Functions and more

Turning one row into multiple rows based on length

Reply
Occasional Contributor
Posts: 15

Turning one row into multiple rows based on length

Hello everyone!
I have a data with a row of phone numbers like this:

Name number
id1 65747 736356 837364 837336
id2 556773 6738373 8373839 677838
.
.
.
I want number column to have length equal to 4.
Name number
id1 6574
Id1 7736
Id1 3568
And so on

Any help will be appreciated.
Super User
Super User
Posts: 9,406

Re: Turning one row into multiple rows based on length

Something like:

data have;
  id=1; number="65747 736356 837364 837336"; output;
  id=2; number="556773 6738373 8373839 677838"; output;
run;

data want (drop=i number);
  set have;
  number=compress(number);
  length want $4.;
  do i=1 to lengthn(number);
    want=cats(want,char(number,i));
    if mod(i,4)=0 then do;
      output;
      want="";
    end;
  end;
run;
PROC Star
Posts: 1,209

Re: Turning one row into multiple rows based on length

something like this.

 

data have;
input Name$1-3 number$5-50;
datalines;
id1 65747 736356 837364 837336
id2 556773 6738373 8373839 677838
;

data want(keep=name num);
	set have;
	comp_number=compress(number);
	nchar=length(comp_number);
	do i=1 to nchar by 4;
		num=substr(comp_number, i, 4);
		output;
	end;
run;
Occasional Contributor
Posts: 15

Re: Turning one row into multiple rows based on length

Thank you both for the help!
Is there a way to not delete spaces?
There is a space between the numbers and I want the space to be retained.
Super User
Super User
Posts: 9,406

Re: Turning one row into multiple rows based on length

This is different to what you asked for in the first post.  Also, you should really show this as wanted output, i.e. what spaces are to be used.  As such you maybe able to modify @draycut's code slightly to:

data have;
id=1; number="65747 736356 837364 837336"; output;
id=2; number="556773 6738373 8373839 677838"; output;
run;

data want (drop=i number);
set have;
length want $4.;
do i=1 to length(number) by 4;
want=substr(number,i,4);
output;
end;
run;

 

PROC Star
Posts: 1,209

Re: Turning one row into multiple rows based on length

@JT99, there doesn't seem to bee spaces in the desired output data you post? Always a good idea to be clear about what your desired data looks like.

Ask a Question
Discussion stats
  • 5 replies
  • 121 views
  • 2 likes
  • 3 in conversation