DATA Step, Macro, Functions and more

Multiple columns have the same condition

Reply
Occasional Contributor
Posts: 13

Multiple columns have the same condition

Hello! My data looks like this:
Acct col1 col2 col3
ABC 45 375 89756
TFA 609 8320 835
FGT 5907 561 413
Col1-col3 are character type.
My code is:
Data final;set cols;
If length(col1)<= 2 then code='02'
Else if lengh(col1)=3 then code ='03;
Else if length(col1)=4 then code ='04';
Newphone1=cats(code,col1);
Run;
How do i make the code simpler so that i wont have to do a similar data step to col2 and col3?
Super User
Posts: 17,864

Re: Multiple columns have the same condition

Super User
Posts: 6,946

Re: Multiple columns have the same condition

Something like this?

data have;
input Acct $ (col1-col3) ($);
cards;
ABC 45 375 89756
TFA 609 8320 835
FGT 5907 561 413
;
run;

data want;
set have;
array cols {*} col1-col3;
array newphone {*} $ newphone1-newphone3;
do i = 1 to 3;
  newphone{i} = cats(put(length(cols{i}),z2.),cols{i});
end;
drop i;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Super User
Super User
Posts: 7,407

Re: Multiple columns have the same condition

Some questions.  Firstly, why are you trying to do this using text numbers?  Numeric data types are there for a reason.  Secondly, what is the reasoning behind this, newphone would end up looking like:

0245

03609

045907

Which doesn't really make sense to me.  What is col1-col3, it looks from the var name newphone, to be a number, but catting on an 02/03 etc. wouldn't make the result a number.  I mean you "could" do:

data have;
  input Acct $ col1 $ col2 $ col3 $;
datalines;
ABC 45 375 89756
TFA 609 8320 835
FGT 5907 561 413
;
run;

data want;
  length newphone $20;
  set have;
  newphone=cats("0",put(lengthn(col1),best.),col1);
run;

But why?

Occasional Contributor
Posts: 13

Re: Multiple columns have the same condition

They are phone numbers. I didnt want to write the whole number because I'm typing on my phone. The whole code is longer than what I wrote here.
Ask a Question
Discussion stats
  • 4 replies
  • 171 views
  • 0 likes
  • 4 in conversation