I have two vectors:a = c(1,2,3)
, b = c(1,2,3)
I want to test whether a
is exactly the same as b
. I know the result can be given by sum(a == b) == length(a)
, but is there any elegant way?
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.
A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.
We can use identical
identical(a,b)
#[1] TRUE
Or if we there are some difference in attributes which we need to avoid in the comparison, use all.equal
all.equal(a,b, check.attributes=FALSE)
#[1] TRUE
Or using similar approach in the OP's post, we can make it compact with all
all(a==b)
#[1] TRUE
The number of characters in the above approach is less...
nchar("identical(a,b)")
#[1] 14
nchar("all(a==b)")
#[1] 9
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