Suppose that I have five vectors:
A<-1:10 B<-1:10 C<-1:10 D<-1:10 E<-1:12
I could test two at a time using identical( ).
identical(A,C)
But I want to test ALL of them at once to see if ANY is different from the others. Is there an easy way to do this?
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.
identical() function in R Language is used to return TRUE when two objects are equal else return FALSE.
1 Answer. To find the common elements from multiple vectors, you can use the intersect function from the sets base R package. vectors (of the same mode) containing a sequence of items (conceptually) with no duplicate values. Intersect will discard any duplicated values in the arguments, and they apply as.
I would just pick one, say A
, and do all pair-wise comparisons with it.
all(sapply(list(B, C, D, E), FUN = identical, A)) # [1] FALSE
Remove the all()
to see the not identical one(s)
sapply(list(B, C, D, E), FUN = identical, A) # [1] TRUE TRUE TRUE FALSE
identical
ought to be transitive, so if A
is identical to C
and to D
, then C
should be identical to D
.
(Thanks to @docendo discimus for simplified syntax.)
First thought is to do unique
on a list of the vectors and check the length. If there are two or more vectors that are different, then the length of the resulting list will be greater than 1.
length(unique(list(A,B,C,D))) == 1 [1] TRUE length(unique(list(A,B,C,D,E))) == 1 [1] FALSE
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