You can use the ANYALPHA function in SAS to return the position of the first alphabetic character in a given string.
This function uses the following basic syntax:
ANYALPHA(expression, [start])
where:
- expression: The string to search
- start (optional): The starting position to search from.
The following example shows how to use this function in practice.
Example: Using the ANYALPHA Function in SAS
Suppose we have the following dataset in SAS that contains information about various employees at some company:
/*create dataset*/
data my_data;
input employeeID $ sales;
datalines;
0054A 23
0009A 38
0018B 40
09H30 12
04429 65
B1300 90
B1700 75
04498 35
0Y009 40
C6500 23
;
run;
/*view dataset*/
proc print data=my_data;
We can use the ANYALPHA function to search for the position of the first alphabetic character in the employeeID column:
/*create new dataset*/
data new_data;
set my_data;
firstAlphaChar = anyalpha(employeeID);
run;
/*view new dataset*/
proc print data=new_data;
The new column called firstAlphaChar displays the position of the first occurrence of any alphabetical character in the employeeID column.
For example, the first alphabetical character in the employee ID of row 1 occurs in the 5th position.
If there are no alphabetical characters for a given employee ID, then a value of 0 is returned.
We can also use the start argument within the ANYALPHA function to specify a starting position to search from.
For example, we can use the following code to search for the position of the first alphabetic character in the employeeID column starting from position 2:
/*create new dataset*/
data new_data;
set my_data;
firstAlphaChar = anyalpha(employeeID, 2);
run;
/*view new dataset*/
proc print data=new_data;
Notice that employeeID values that only contain an alphabetical character in the first position now receive a value of 0 in the firstAlphaChar column since the search for alphabetical characters now starts at position 2.
Additional Resources
The following tutorials explain how to use other common functions in SAS:
How to Remove Special Characters from Strings in SAS
How to Replace Characters in a String in SAS
How to Convert Character Variable to Numeric in SAS