简体   繁体   中英

Compare two vector in 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?

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

In addition to the answer above; you could also consider the package 'compare'.

library(compare)
compareEqual(a,b)#TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM