R Program to Find Index of an Element in a Vector

Example 1: Find Index Value of R Vector Element Using match()

# create two strings
vowel_letters <- c("a", "e", "i", "o", "u")

# find index value of "i"
match("i", vowel_letters) # 3

# find index value of "u"
match("u", vowel_letters) # 5

Output

[1] 3
[1] 5

In the above example, we have used the match() function to find the index of an element in the vector named vowel_letters.

Here,

  1. "i" is present in vowel_letters at the 3rd index, so the method returns 3
  2. "u" is present in vowel_letters at the 5th index, so the method returns 5

Example 2: Find Index Value of R Vector Element Using which()

# create two strings
languages <- c("R", "Swift", "Java", "Python")

# find index value of "Swift" using which()
which(languages == "Swift") # 2

# find index value of "Python" using which()
which(languages == "Python") # 4

Output

[1] 2
[2] 4

Here, we have used the which() function to find the index value of an element.

Since,

  1. "Swift" is present in languages at the 2nd index, so the method returns 2
  2. "Python" is present in languages at the 4th index, so the method returns 4