Substring in sas – extract first n & last n character

Substring in SAS is accomplished by using SUBSTR() Function. SUBSTR() Function takes up the column name as argument and calculates the substring. Extract first N Character and Extract Last N Characters in SAS is accomplished using SUBSTR() Function.

  • Extract First N Characters in SAS using SUBSTR() Function
  • Extract Last N Characters in SAS using SUBSTR() Function

So we will be using EMP_DET Table in our example

Substring in sas - extract first n & last n character 1

 

Substring in sas – extract first n character

SUBSTR() Function takes up the column name as argument followed by start and length of string and calculates the substring. We have extracted first N character in SAS using SUBSTR() function as shown below

/* substring in sas - extract first n character */ 
data emp_det1; 
set emp_det; 
state_new =SUBSTR(state,1,6); 
run;

So the resultant table will be

Substring in sas - extract first n & last n character 2

 

Substring in sas – extract last n character : Method 1

SUBSTR() Function takes up the column name as argument followed by start and length of string  and calculates the substring. We have extracted Last N character in SAS using SUBSTR() Function and TRIM() Function as shown below


/* substring in sas - extract last n character - method 1 */ 

data emp_det1; 
set emp_det; 
state_code =SUBSTR(trim(state),length(trim(state))-2); 
run;

So the resultant table will be

Substring in sas - extract first n & last n character 3

 

 

Substring in sas – extract last n character : Method 2

In second method We have extracted Last N character in SAS using SUBSTR() Function and Reverse() Function as shown below. This is roundabout way to extract substring from column name. First reverse and first substring and then reverse back

/* substring in sas - extract last n character - method 2 */ 

data emp_det1; 
set emp_det; 
Newvar=reverse (substr(reverse(strip(state)),1,2)); 
run;

So the Resultant table will be

Substring in sas - extract first n & last n character 4

 

                                                                                   

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.