SUBSTR() Function | SAS Functions

SUBSTR Function (pronounced as “substring”) is used to extract string from a specific position or positions of characters within a character variable. This function can be used in either side of the “=” sign in a data step statement.


Syntax of substr()

variable_name = substr(SOURCE,START POSITION,Number of characters);


SOURCE — This is the larger or reference string. It can be a variable or a string of characters.

START POSITION — This value is a positive integer and references the starting point to begin reading the internal group of characters.

Number of characters — This value is a positive integer and references the number of characters to read from the starting point POSITION in the field SOURCE, we can leave this argument blank if we want to extract the string till the last available character.

Example 1 (All Three Argument)- 

data a;
    input Name $;
    First_four = substr(Name,1,4);
    cards;
Substrting 
Example
;
run;

substr function in SAS 

Fact -
If the substr creates a new variable then the length of the new variable would be same as that of parent variable


Example 2 (Two Argument) - 

data a;
input Name $;
First_four=substr(Name, 2);
cards;
Substrting 
Example
;
run;

It Extracted from 2nd position to End of the string - See below output 

substr function in SAS



SUBSTR Function on Left side of = 

If Substr function is used on the left side of the = sign then it is used to replace the values, Suppose in below example you need to change the first two values from 91 to 00,  this can be done using substr -

Example 3 (Substr function on left side of "=") - 

data a;
x='(91) 9999265789';
Y=x;
substr(y, 2, 2)='00';
run;

substr on left side

Post a Comment

0 Comments