SUBSTR is normally used to break up a long string of text into different pieces of information.
This dataset contains some of the subject codes used in a University. We are going to break them into subject (first 3 letters) and subject number (last 3 numbers).
Subject = Substr( Code, 1, 3);
Subject_no = Substr( Code, 4, 3);
The Substr function contains 3 arguments:
Start: The starting position to begin reading the variable.
Length: Number of character to read
As you can see in our example, ‘Subject’ extracts the portion of the ‘Code’ variable from the 1st position to the 3rd position; while ‘Subject_no’ extracts the portion from the 4th position to the 6th position.
DONE! You have learned the SUBSTR function in SAS!
- If you want to read the variable till the end of the text such as what we did with the Subject_no variable, you can drop the last argument:
Subject_no = Substr( Code, 4);
This function will return the same result.
- SUBSTR function can also be used in combination with the INDEX function. We will explain this shortly in later section of this lesson.