You can use the SUBSTR function in SAS to extract a portion of a string.
This function uses the following basic syntax:
SUBSTR(Source, Position, N)
- Source: The string to analyze
- Position: The starting position to read
- N: The number of characters to read
The value for the Position argument specifies the starting position from the left of the string.
To instead specify a starting position from the right of the string, you can use the following syntax:
data new_data; set original_data; last_three = substr(team, length(team)-2, 3); run;
This particular example creates a new variable called last_three that extracts the last three characters from the right of the string variable called team.
The following example shows how to use this syntax in practice.
Example: Extract Substring from Right in SAS
Suppose we have the following dataset in SAS that contains information about various basketball teams:
/*create dataset*/ data original_data; input team $ points; datalines; Mavericks 104 Thunder 99 Rockets 116 Spurs 98 Pistons 99 Pelicans 105 Warriors 119 Blazers 113 Nuggets 100 Kings 123 ; run; /*view dataset*/ proc print data=original_data;
We can use the following code to extract the last 3 characters from the team variable:
/*create new dataset*/ data new_data; set original_data; last_three = substr(team, length(team)-2, 3); run; /*view new dataset*/ proc print data=new_data;
Notice that the column called last_three contains the last three characters from the team column.
We can also easily change the values in the SUBSTR function to extract a different number of characters from the right side of the string.
For example, we can use the following syntax to extract the last five characters from the right:
/*create new dataset*/ data new_data; set original_data; last_five = substr(team, length(team)-4, 5); run; /*view new dataset*/ proc print data=new_data;
Notice that the column called last_five contains the last five characters from the team column.
The following tutorials explain how to perform other common tasks in SAS: