Suppose I have a list y, and I want to return to position of the first instance of every element of another list x=c('a','b','c') (i.e. the position of the first a, the first b, etc).

Using

which(y %in% x) 

will simply return all instances rather than the first instance. Another approach is to loop over all elements xi in x and use

min(which(y == xi))

Is there a way to do this without using a for loop over the elements in x? I've found several queries on stackoverflow on how to find the first instance of a single element in a list, but not for multiple elements.

upvote
  flag
Possible duplicate of Finding Elements of Lists in R – User632716
upvote
  flag
The linked thread deals with a somewhat different question. I know how to match list elements, I'm asking specifically how to return the first instance of each element of one list in another list being queried. – Max

1 Answers 11

up vote 0 down vote accepted

I would use the map function in the purrr package to do this:

indices <- purrr::map(x, function(i){
  min(which(y == i))
})
upvote
  flag
I'm not familiar with the purrr library, but this does work, thanks. – Max
upvote
  flag
it is similar to the apply family of functions but has more consistent syntax than the apply family – tbradley

Not the answer you're looking for? Browse other questions tagged or ask your own question.