BookmarkSubscribeRSS Feed
Zizie
Calcite | Level 5

I have a data with different length character. I want to have 2 first character for example '1232' to become '12'

 

data b;

set a;

new1=substr(LOAN_APPLCTN_BNM_CODE,1,3);

run;

4 REPLIES 4
Kurt_Bremser
Super User

The third parameter of the substr() function is the length to be extracted, so it should be "2" in your case.

Another merthod is to forgo the substr() altogether and define the new variable with the wanted length, causing an implicit truncation:

data _null_;
LOAN_APPLCTN_BNM_CODE = "1232";
length new1 $2;
new1 = LOAN_APPLCTN_BNM_CODE;
put new1=;
run;

Log:

27         data _null_;
28         LOAN_APPLCTN_BNM_CODE = "1232";
29         length new1 $2;
30         new1 = LOAN_APPLCTN_BNM_CODE;
31         put new1=;
32         run;

new1=12
Zizie
Calcite | Level 5
thank you.

data b;
set a;

LENGTH NEW1 $2;
NEW1=left(new);
RUN;
Zizie
Calcite | Level 5
Can I use the same method if it is numeric value
Kurt_Bremser
Super User

With a numeric value, you have to take care of the conversion from numeric to character. substr() is a character function.

If you always have 4 digits, you could keep it numeric:

data _null_;
LOAN_APPLCTN_BNM_CODE = 1232;
new1 = int(LOAN_APPLCTN_BNM_CODE/100);
put new1=;
run;

Log:

27         data _null_;
28         LOAN_APPLCTN_BNM_CODE = 1232;
29         new1 = int(LOAN_APPLCTN_BNM_CODE/100);
30         put new1=;
31         run;

new1=12

"Clean" programming (see Maxim 25) mandates the avoidance of implicit type conversions (and the corresponding NOTEs in the log):

data _null_;
LOAN_APPLCTN_BNM_CODE = 1232;
new1 = substr(left(put(LOAN_APPLCTN_BNM_CODE,4.)),1,2);
put new1=;
run;

Log:

27         data _null_;
28         LOAN_APPLCTN_BNM_CODE = 1232;
29         new1 = substr(left(put(LOAN_APPLCTN_BNM_CODE,4.)),1,2);
30         put new1=;
31         run;

new1=12

Catch up on SAS Innovate 2026

Nearly 200 sessions are now available on demand with the SAS Innovate Digital Pass.

Explore Now →
Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 4 replies
  • 8022 views
  • 1 like
  • 2 in conversation