Get the index of the values of one vector in another?

后端 未结 2 429
孤街浪徒
孤街浪徒 2020-12-05 18:05

I would guess this is a duplicate, but I can\'t find that so here goes...

I\'d like to return the index of second in first:

first = c( \"a\" , \"c\"          


        
相关标签:
2条回答
  • 2020-12-05 18:23

    I was solving related problem, selecting the elements of a vector based on a pattern. Lets say we have vector 'a' and we would like to find the occurrences of vector 'b'. Can be used in filtering data tables by a multiply search patterns.

    a=c(1, 1, 27, 9, 0, 9, 6, 5, 7)
    b=c(1, 9)
    
    match(a, b)
    [1] 1  1 NA  2 NA  2 NA NA NA
    

    So match() it is not really useful here. Applying binary operator %in% is more convenient:

    a %in% b
    [1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
    
    a[a %in% b]
    [1] 1 1 9 9
    

    Actually from the match() help %in% is just a wrap around match() function:

    "%in%" <- function(x, table) match(x, table, nomatch = 0) > 0
    
    0 讨论(0)
  • 2020-12-05 18:32

    Getting indexes of values is what match() is for.

     first = c( "a" , "c" , "b" )
     second = c( "c" , "b" , "a" )
     match(second, first)
     [1] 2 3 1
    
    0 讨论(0)
提交回复
热议问题