Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vector in R

Tags:

r

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?

like image 254
Dylan Avatar asked Jun 02 '16 02:06

Dylan


People also ask

How do you compare two vectors the same in R?

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 you find a match between two vectors 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.

How do you compare two vectors?

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.


1 Answers

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
like image 197
akrun Avatar answered Oct 07 '22 13:10

akrun