How to find out the index of an element present in a vector in R? Explain with an example

474    Asked by Aashishchaursiya in Data Science , Asked on Dec 4, 2019

To find out the index of an element, we have a function called match which returns the first encounter of a match. Let us define a vector of 10 random elements.

random_samples <- sample(1:10)

Random_samples

Output

[1] 10 9 6 8 1 3 4 7 5 2

Now we will apply match to find out the index

match(c(4,8),random_samples)

Output

[1] 7 4

In case if we want multiple matching, we can use a pipe operator as follows

random_samples<- sample(1:4,10,replace=TRUE)

random_samples

[1] 1 2 2 2 1 1 1 2 2 4

which(random_samples %in% c(2,4))



Your Answer

Interviews

Parent Categories