Logo

Is there an R function for finding the index of an element in a vector?

If you want the position of all occurrences of a value in a vector, use:

vec <- c("a", "b", "c", "b", "a") which(vec == "b")

This returns the indices of every "b" in the vector.

Using match()
If you only need the first match’s index:

match("b", vec)

This returns the index of the first "b" and ignores subsequent matches.

Pro Tips

  • which() returns all matching positions as a numeric vector.
  • match() returns the position of the first match, or NA if not found.
  • If multiple values are specified, match() can handle a vector of search terms, returning the first match for each.

Further Learning
Looking to sharpen your coding skills for interviews or big-picture system design? Explore these resources from DesignGurus.io:

You can also get personalized feedback from ex-FAANG engineers via the Coding Mock Interview platform. For quick tutorials and tips, check out the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind