To get a substring from the right in a SAS data step, you can use the SAS substr() function and specify a start position with help from the length function.
data k;
var = "string";
last_two_chars = substr(var, length(var) - 2,2);
all_but_last_two = substr(var, 1, length(var) - 2);
put substr_from_right=;
run;
/* Output */
last_two_chars=ng
all_but_last_two=stri
When working with character variables in SAS, the ability to manipulate and get information from these variables is valuable.
One such piece of information are substrings of a variable.
The SAS substr() function allows us to easily get substrings from our variables in data steps.
substr() takes in 3 arguments. The first argument is the string you want to extract a substring from. The second argument is the starting position of your substring. For the third argument, you provide the number of characters you want to read.
If you want to get a substring of a string and start from the right of the string, we can use substr() and use length() to pass different second and third arguments.
For example, if you want to get all characters except the last two characters of a string, you can use the length() function and subtract two from it as shown below.
data k;
var = "string";
all_but_last_two = substr(var, 1, length(var) - 2);
put substr_from_right=;
run;
/* Output */
all_but_last_two=stri
If you instead want to get just the last two characters from a string, you can start your substring at the length of the variable minus two position and go for two characters as shown below.
data k;
var = "string";
last_two_chars = substr(var, length(var) - 2,2);
put substr_from_right=;
run;
/* Output */
last_two_chars=ng
Hopefully this article has been useful for you to learn how to get a substring from the right of a character variable in SAS.