Home > Software design >  R function like which to match multiple inputs to multiple values
R function like which to match multiple inputs to multiple values

Time:11-23

I have a vector of multiple values that I want to match to multiple values without the use of a loop. Is there a function that can do this?

x <- c(2,5,4)
y <- 2:10
which(x==y) #won't work

Expected output is 1,4,3

In my real use case, you can assume that there is only 1 correct match and it will match y every time. I need this to be as fast as possible, that's why I'm trying to avoid a loop. As a side note, this part is already inside of a foreach loop.

CodePudding user response:

You want match

match(x,y)

# 1 4 3

CodePudding user response:

The which() version would be which(x %in% y). But I don't think this fits for your purpose as the expected output is 1,2,3.

But if you apply which(y %in% x) than your output will be 1,3,4

  • Related