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

前端 未结 5 1315
予麋鹿
予麋鹿 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:56

    In lieu of a cleaner alternative, here's the known solution:

    SameElements <- function(a, b) return(identical(sort(a), sort(b)))
    SameElements(c(1, 2, 3), c(1, 3, 2))  # TRUE
    SameElements(c(1, 2, 3), c(1, 1, 3, 2))  # FALSE
    

    Edit: identical instead of all.equal(...) == T per nrussell's suggestion.

提交回复
热议问题