How do you use the INDEX Function in SAS (With Examples)?

The INDEX function in SAS is used to look up a value in an array and return the position (index) or element of the array or data set. It is useful for when you need to find the position of a value in a data set. For example, you can use the INDEX function to find the position of a particular value in a character array. To do this, you would use the syntax: INDEX(array, ‘value_to_find’). This would return the index of the value in the array. You can also use the INDEX function to look up the element of an array or data set. To do this syntax, you would use: INDEX(array, index_to_find). This would return the element at the specified index of the array.


You can use the INDEX function in SAS to return the position of the first occurrence of a string within another character string.

This function uses the following basic syntax:

INDEX(source, excerpt)

where:

  • source: The string to analyze
  • excerpt: The string of characters to search for within source

The following example shows how to use this function in practice.

Example: Using the INDEX Function in SAS

Suppose we have the following dataset in SAS that contains a column of names:

/*create dataset*/
data original_data;
    input name $25.;
    datalines;
Andy Lincoln Bernard
Barren Michael Smith
Chad Simpson Arnolds
Derrick Smith Henrys
Eric Millerton Smith
Frank Giovanni Goode
;
run;

/*view dataset*/
proc print data=original_data;

We can use the INDEX function to search for the position of the first occurrence of the string “Smith” in each row:

/*find position of first occurrence of 'Smith' in name*/
data new_data;
    set original_data;
    first_smith = index(name, 'Smith');
run;

/*view results*/
proc print data=new_data;

The new column called first_smith displays the position of the first occurrence of the string ‘Smith’ in the name column.

If ‘Smith’ is not found at all, the INDEX function simply returns a value of 0.

It’s important to note that the INDEX function is case-sensitive, so if you search for ‘smith’ instead, the INDEX function will return 0 for each string:

/*find position of first occurrence of 'smith' in name*/
data new_data;
    set original_data;
    first_smith = index(name, 'smith');
run;

/*view results*/
proc print data=new_data;

To perform a case-insensitive search, you can use the function to first convert each string to all lowercase and then search for ‘smith’ as follows:

/*find position of first occurrence of 'smith' in name*/
data new_data;
    set original_data;
    first_smith = index(lowcase(name), 'smith');
run;

/*view results*/
proc print data=new_data;

By first converting each string to all lowercase, we’re able to use the INDEX function to perform a case-insensitive search.

The following tutorials explain how to use other common functions in SAS:

x