Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using identical() in R with multiple vectors

Tags:

r

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?

like image 952
Andy Avatar asked Jun 15 '15 16:06

Andy


People also ask

How do you check if two vectors are identical 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.

What does identical function do in R?

identical() function in R Language is used to return TRUE when two objects are equal else return FALSE.

How do you find the common element of multiple vectors?

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.


2 Answers

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.)

like image 88
Gregor Thomas Avatar answered Sep 21 '22 09:09

Gregor Thomas


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 
like image 20
cdeterman Avatar answered Sep 21 '22 09:09

cdeterman