[R] Is there a neat R trick for this?
Berend Hasselman
bhh at xs4all.nl
Tue Feb 12 11:17:16 CET 2013
On 12-02-2013, at 11:09, Robert Latest <boblatest at gmail.com> wrote:
> Hello all,
>
> given two vectors X and Y I'd like to receive a vector Z which
> contains, for each element of X, the index of the corresponding
> element in Y (or NA if that element isn't in Y).
>
> Example:
>
> x <- c(4,5,6)
> y <- c(10,1,5,12,4,13,14)
>
> z <- findIndexIn(x, y)
> z
> [1] 5 3 NA
>
> 1st element of z is 5, because the 1st element of x is at the 5th position in y
> 2nd element of z is 3, because the 2nd element of x is at the 3rd position in y
> 3rd element of z is NA, because the 3rd element of x is not in y
>
> Of course I can write the function findIndexIn() using a for loop, but
> in 80% of cases when I felt the urge to use "for" in R it turned out
> that there was already some builtin operator or function that did the
> trick.
>
> Suggestions, anyone?
> Thanks,
>
?match
match(x,y)
Berend
More information about the R-help
mailing list