Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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) should satisfy these criteria:

SameElements(c(1, 2, 3), c(1, 2, 3))  # TRUE SameElements(c(1, 2, 3), c(3, 2, 1))  # TRUE SameElements(c(1, 2, 1), c(1, 2))  # FALSE SameElements(c(1, 1, 2, 3), c(3, 2, 1))  # FALSE 

Edit 1: Specified that function should return F when the vectors contain the same elements, but with different frequencies.

Edit 2: Cleaned up question to omit initial answer, as this is now in my actual answer.

like image 739
Max Ghenis Avatar asked Jan 12 '15 23:01

Max Ghenis


People also ask

How do you check if two vectors are the same in R?

Check if Two Objects are Equal in R Programming – setequal() Function. setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.

How do I match a vector in R?

R Match – Using match() and %in% to compare vectors We have two options here: The R match () function – returns the indices of common elements. the %in% operator – returns a vector of True / False results which indicates if a value in the first vector was present in the second.


2 Answers

I think you can use setequal(a,b)

Updated update setequal checks if two vectors are composed of the same elements but it does not check if these elements have the same occurrences in each vector.

like image 76
Marat Talipov Avatar answered Sep 17 '22 17:09

Marat Talipov


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.

like image 45
Max Ghenis Avatar answered Sep 20 '22 17:09

Max Ghenis