R Program to Find Index of an Element in a Vector
[This article was first published on   R feed, and kindly contributed to R-bloggers].  (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
              Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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,
- "i"is present in vowel_letters at the 3rd index, so the method returns 3
- "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,
- "Swift"is present in languages at the 2nd index, so the method returns 2
- "Python"is present in languages at the 4th index, so the method returns 4
To leave a comment for the author, please follow the link and comment on their blog:  R feed.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
