Find all positions of all matches of one vector of values in second vector

后端 未结 2 1987
[愿得一人]
[愿得一人] 2020-12-11 04:54

I need to find all positions in my vector corresponding to any of values of another vector:

needles <- c(4, 3, 9)
hay <- c(2, 3, 4, 5, 3, 7)
mymatches(         


        
相关标签:
2条回答
  • 2020-12-11 05:21

    This should work:

    which(hay %in% needles) # 2 3 5
    
    0 讨论(0)
  • 2020-12-11 05:26

    R already has the the match() fn / %in% operator, which are the same thing, and they're vectorized. Your solution:

    which(!is.na(match(hay, needles)))
    [1] 2 3 5
    

    or the shorter syntax which(hay %in% needles) as @jalapic showed.

    With match(), if you wanted to, you could see which specific value was matched at each position...

    match(hay, needles)
    [1] NA  2  1 NA  2 NA
    

    or a logical vector of where the matches occurred:

    !is.na(match(hay, needles))
    [1] FALSE  TRUE  TRUE FALSE  TRUE FALSE
    
    0 讨论(0)
提交回复
热议问题