Check whether two vectors contain the same (unordered) elements in R

前端 未结 5 1318
予麋鹿
予麋鹿 2021-01-01 11:24

I\'d like to check whether two vectors contain the same elements, even if they\'re not ordered the same. For example, the function (let\'s call it SameElements)

5条回答
  •  不知归路
    2021-01-01 11:34

    Basically your problem can be outlined in those steps :

    if not same unique values: return FALSE
    else if same Frequencies: return TRUE
        else return True
    

    In proper R code :

    SameElements = function(v1, v2)
    {
      tab1 = table(v1) ; tab2 = table(v2)
      if( !all(names(tab1) == names(tab2)) ) return(FALSE) # Same unique values test
      return(all(tab1==tab2)) # Same frequencies test
    }
    

    Some examples :

    v1 = c(1, 2, 3)
    v2 = c(3, 2, 1)
    SameElements(v1, v2) # TRUE as both uniqueness and frequencies test are verified
    
    v1 = c(1,1, 2,3)
    v2  =c(3,2,1)
    S
    

    ameElements(v1, v2) # FALSE as frequencies test is violated

    PS : i) You can replace !all() by any()
    ~~~ii) To speed up the code you can quickly return FALSE when the two vectors don't
    ~~~have the same length, thus avoiding frequencies computation.

提交回复
热议问题