SAS day 6 : Substr
SAS Substr is a common function for building datasets. It is used for extracting partial information from variables.
Syntax:
SUBSTR(variable, position, desired length)
Substr extracts a substring from a variable starting at “position” for “desired length” characters.
Example:
In ADPE, we use substr to create pevisit.
VISIT: CYCLE 10 DAY 1
pevisit= substr(VISIT, 1, 8)
pevisit: CYCLE 10
Problem:
Now we want to extract the records of variable a that have “.1” as the last two digits. Note the length varies for each record.
1CYCLE 1 DAY 1
2CYCLE 1 DAY 8
3CYCLE 1 DAY 28
4CYCLE 1 DAY 28.1
R391n4 / Pixabay
Solution:
1. Apply Stripcommand to remove the ending empty space for variable a.
2. Apply Reverse to reserve the order the variable a
3. Apply Substr to extract the first two digits.
Code:
substr(reverse(strip(visit)), 1 ,2)=”1.”
Output:
CYCLE1 DAY 28.1
an alternative solution would use Index function.
Happy SAS Coding!