Re: [R] string vector indices

From: Marc Schwartz <>
Date: Sun 16 Apr 2006 - 23:52:27 EST

On Sun, 2006-04-16 at 11:48 +0200, Philipp Pagel wrote:
> On Sun, Apr 16, 2006 at 12:26:29AM -0400, Luke wrote:
> >
> > x <- "a", "aab"
> > y <- "a", "aa", "aab", "aabc".
> >
> > Is there any R function to get the indices of y for the elements of x, that
> > is, foo(x, y) will give me the index vector c(1, 3)?

> match(x, y)
> cu
> Philipp

Just a quick note here that there is one limitation in using match(), which is that it will only return the index of the first match.

So, if there was an element in 'x' that appeared more than once in 'y', you would still only get c(1, 3):

x <- c("a", "aab")
y <- c("a", "aa", "aab", "aabc", "a")

> match(x, y)
[1] 1 3

Note that the second occurrence of "a" in 'y' is not picked up.

To solve this problem use %in% combined with which():

> which(y %in% x)

[1] 1 3 5

See ?which and ?"%in%" for more information. Note that the help for %in% is on the same page as ?match.

This approach will work in both situations.

HTH, Marc Schwartz mailing list PLEASE do read the posting guide! Received on Mon Apr 17 00:26:46 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Mon 17 Apr 2006 - 02:09:41 EST.

Mailing list information is available at Please read the posting guide before posting to the list.