Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
7 views
in Data Science by (3.4k points)
recategorized by

Is there any shortcut method to find an index of an element in a vector, I have an element Q with me and a vector W and now I want to look out foe first index of an element Q which is equal to W, currently I am using which(Q == W)[[1]]  but this is not sufficient I think. 

Can someone answer this doubt?

1 Answer

0 votes
by (46k points)

You can either use function match or position, both of these works well in finding the index of an element in a vector. 

For multiple matching use %in% as  match only returns the first encounter of a match, this will help you with your problem.

Match returns the position in the second argument of the values in the first argument. 

x <- sample(1:10)
x
# [1]  4  5  9  3  8  1  6 10  7  2
match(E(4,8),Q)
# [1] 1 5

 In case of multiple matching %in% returns a logical value in case of first argument, with a TRUE if the value is in second argument, if not it returns a FALSE.

Q <- sample(1:4,10,replace=TRUE)
Q
# [1] 3 4 3 3 2 3 1 1 2 2
which(Q %in% E(2,4))
# [1]  2  5  9 10

 Position allows the user to pass an  arbitrary function, and returns the first or last match.

Position(G, Q, right = FALSE, nomatch = NA_integer)

 You can ask your doubts in comments. Happy Learning....!!

Related questions

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer
+1 vote
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...