Hello guys,
This is a bit tricky. I am trying to add leading zeros to a variable (numvar) depending on the length of charVar variable.
For example, in the data below, the first row is charVar=1000 so its length is 4, hence I want to add just one zero before numVar.
I tried put(numvar, z4.) approach but this wont work for the second row. I also tried CALL SYMPUT and then symget but it is not working either.
Any idea on how this can be accomplished will be highly appreciated.
charVar | numvar | Length_charVar | wantVarLeadingzeros |
1000 | 200 | 4 | 0200' |
10000 | 500 | 5 | 00500' |
Use PUTN() function since it takes an expression for the format.
data have ;
input charVar :$20. numvar Length_charVar wantVarLeadingzeros :$20.;
cards;
1000 200 4 0200
10000 500 5 00500
;
data want ;
set have ;
length VarLeadingzeros $20 ;
VarLeadingzeros=putn(numvar,cats('z',Length_charVar,'.'));
run;
char Length_ wantVar Var Obs Var numvar charVar Leadingzeros Leadingzeros 1 1000 200 4 0200 0200 2 10000 500 5 00500 00500
PUTC/PUTN will take a character variable as the format. PUT will not.
data want;
set have;
y=lengthn(put(rvar, 8. -l));
formatc=catt('Z', y);
want = putn(numvar, formatc);
run;
@rosegarden81 wrote:
Hello guys,
This is a bit tricky. I am trying to add leading zeros to a variable (numvar) depending on the length of charVar variable.
For example, in the data below, the first row is charVar=1000 so its length is 4, hence I want to add just one zero before numVar.
I tried put(numvar, z4.) approach but this wont work for the second row. I also tried CALL SYMPUT and then symget but it is not working either.
Any idea on how this can be accomplished will be highly appreciated.
charVar numvar Length_charVar wantVarLeadingzeros 1000 200 4 0200' 10000 500 5 00500'
just for fun:
data have;
input charVar $ numvar Length_charVar ;
cards;
1000 200 4 0200'
10000 500 5 00500'
;
data want;
set have;
_iorc_=Length_charVar-length(put(numvar,8. -l));
want=cats(repeat('0',_iorc_-1),numvar);
run;
Use PUTN() function since it takes an expression for the format.
data have ;
input charVar :$20. numvar Length_charVar wantVarLeadingzeros :$20.;
cards;
1000 200 4 0200
10000 500 5 00500
;
data want ;
set have ;
length VarLeadingzeros $20 ;
VarLeadingzeros=putn(numvar,cats('z',Length_charVar,'.'));
run;
char Length_ wantVar Var Obs Var numvar charVar Leadingzeros Leadingzeros 1 1000 200 4 0200 0200 2 10000 500 5 00500 00500
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.
Ready to level-up your skills? Choose your own adventure.