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;

Example 1:

data saslib.learnsubstr;
set sashelp.class;
x = substr(name,4,3);
length y $5.;
select (x);
when (“red”,”ce”,”c”) y = “A100”;
otherwise y = “B200”;
end;
put _all_;
run;

 

sas substr SAS SUBSTR / SUBSTRN – SAS Base Programming substr 1

Example 2:

data learnsubstr;
set sashelp.class;
x = substr(name,4,3);
length y $5.;
if x = “red” then y = “100”;
else y = “200”;
put _all_;
run;

sas substr SAS SUBSTR / SUBSTRN – SAS Base Programming substr 1

Example 3

data saslib.learnsubstr;
set sashelp.class;
x = substr(name,4,3);
length y $5.;
if x = “red” or x = “ce” or x = “e” then y = “A100”;
else y = “Z200”;
put _all_;
run;

sas substr SAS SUBSTR / SUBSTRN – SAS Base Programming substr example 3

Example 4:

data saslib.learnsubstr;
set sashelp.class;
x=substr(name, 4, 3);
length y $5.;
if x in (“red”, “ce”, “e”) then y=”A100″;
else y=”B200″;
put _all_;
run;

sas substr SAS SUBSTR / SUBSTRN – SAS Base Programming substr example 4

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts