Sentry Page Protection
SAS Functions [10-14]
INDEX Function
You can use the INDEX function to search for a text or phrase from a character variable.
Let's take a look at the following example:
The EXAMPLE data set above contains a sentence.
[Reminder: To see the EXAMPLE data set on SAS Studio, run the code in the yellow box above]
Now, we're going to use the INDEX function to search for the word "SAS" from the sentence.
Example
Data Example2;
Set Example;
Ind = Index(Text, "SAS");
Run;
In this example, the INDEX function looks for the word "SAS" from the Text variable.
The function found it at the 11th position, and thus, returns the numeric value of 11.
KEY CONCEPT #1
If the word is not found from the variable, the INDEX function will return the value of 0.
Example
Data Example3;
Set Example;
Ind = Index(Text, "training");
Run;
KEY CONCEPT #2
The case IS sensitive when using the INDEX function.
Searching for the word "sas" is different than searching for the word "SAS".
Example
Data Example4;
Set Example;
Ind = Index(Text, "sas");
Run;
The INDEX function returns the value of 0 because "sas", in lower case, is not found from the Text variable.
Exercise
Copy and run the MATHEXAM data set from the yellow box below.
Write a SAS program to extract the numeric exam result from the COMMENT variable.
E.g.
Mary's exam result is 89 --> 89
Only the exam result (numeric value) should be extracted.
Create any data set or variables if necessary.
Need some help?
HINT:
This question is a little tricky. You will need to use the SUBSTR function to extract the result. Use the INDEX function to identify the starting position for extraction.
SOLUTION:
Data MathExam2;
Set MathExam;
Ind = Index(Comment, "is ");
pos = Ind+3;
Result = substr(Comment, pos);
Run;
Note: the text in the INDEX function is "is ". There is a space after the word "is".
Fill out my online form.