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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With