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, orNA
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:
- Grokking the Coding Interview: Patterns for Coding Questions to master pattern-based problem solving.
- Grokking Data Structures & Algorithms for Coding Interviews for robust algorithmic foundations.
- Grokking System Design Fundamentals if you’re aiming to build or analyze scalable systems.
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