0

Let's say that we have two vectors:

x <- c("1", "5", "8")
y <- c("1", "2", "3", "4", "5", "6", "7", "8")

I want to obtain indexes of y in which y equals x.

My code is:

x <- c("1", "5", "8")
y <- c("1", "2", "3", "4", "5", "6", "7", "8")
which(y == x) 
> which(y == x)
[1] 1 5
Warning message:
In y == x : longer object length is not a multiple of shorter object length

And it's kind of logical because those two are not same length, however I have no idea how can I do this without any loop. Do you have any idea how it can be performed ?

John
  • 1,849
  • 2
  • 13
  • 23

2 Answers2

1

You could try this solution. match function finds the position of each element of x in y.

match(x, y)
0

Use which(y %in% x) as %in% will match every element of y with every element of x and return indices

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45