Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In R, I have an element x and a vector v. I want to find the first index of an element in v that is equal to x. I know that one way to do this is: which(x == v)[[1]], but that seems excessively inefficient. Is there a more direct way to do it?

For bonus points, is there a function that works if x is a vector? That is, it should return a vector of indices indicating the position of each element of x in v.

like image 255
Ryan C. Thompson Avatar asked Apr 07 '11 07:04

Ryan C. Thompson


People also ask

How do you find the index of an element in a vector in R?

Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.

How do you access index in R?

Vector elements are accessed using indexing vectors, which can be numeric, character or logical vectors. You can access an individual element of a vector by its position (or "index"), indicated using square brackets. In R, the first element has an index of 1.

What is index function R?

Returns an INTEGER value that indicates the position of the target string within the source string.


2 Answers

The function match works on vectors:

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

match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

For multiple matching, %in% is the way to go:

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

%in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise.

like image 137
Joris Meys Avatar answered Sep 22 '22 21:09

Joris Meys


the function Position in funprog {base} also does the job. It allows you to pass an arbitrary function, and returns the first or last match.

Position(f, x, right = FALSE, nomatch = NA_integer)

like image 20
pedroteixeira Avatar answered Sep 23 '22 21:09

pedroteixeira