The SAS SUBSTR function differs from the substring function in other programming languages as it can be used on either side of the assignment operator. The SAS SUBSTR() / SUBSTRN() function works only for character variables. To make it run for numeric variables, we first need to convert numeric variables to character variables with PUT() function.
newvar= SUBSTR(char_var,start,length);newvar= substr(variable, starting position, # of characters we want to retrieve);
newvar= SUBSTR (char_string, start_position,no_of_chars_to_read );
RIGHT SIDE APPLICATION – SAS SUBSTR
In this example, we are going to assign the area code of a mobile
number to a variable called AREA_CODE.
%let phone = (917) 422-9470 ;
data _null_ ;
phone = ‘(917) 422-9470’ ;
area_code = substr(phone, 2, 3) ;
area_code = substr(‘(917) 422-9470’, 2, 3) ;
area_code = substr(“&phone”, 2, 3) ;
run ;
LEFT SIDE APPLICATION – SAS SUBSTR
Suppose you want to change just a few characters of a variable—
use the SUBSTR function on the left side of the assignment
statement.
data _null_ ;
phone = ‘(544) 843-9078’ ;
substr(phone, 2, 3) = ‘998’ ;
run;