Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare multiple vectors at the same time in R?

I can easily compare 2 vectors in R to see how many elements are the same. Say

  a<- c(1,2,3,4)
  b<- c(1,2,3,5)
  sum(a==b) would give me what I want

But how can I compare 3 vectors ? or more than 3 vectors at the same time ?

  a<- c(1,2,3,4)
  b<- c(1,2,3,5)
  c<- c(2,3,4,5)
  sum(a==b & b==c) # does not seem to be correct

I am looking for whether elements are same in the same position. In the same case, it would give me zero since a, b, c are not all the same at same position.

count = 0
for(i in 1:length(a)){
  if((a[i]==b[i]) & (a[i]==c[i]))
  count=count+1
} # this will give me that I want, but the efficiency seems very low 
like image 843
GeekCat Avatar asked Dec 14 '14 14:12

GeekCat


2 Answers

Create a matrix or data.frame and check whether one of the column is equal to the rest.

 m1 <- cbind(a,b,c)
 sum(rowSums(m1==m1[,1])==ncol(m1))
 #[1] 0

Or

 sum(Reduce(`&`,Map(`==`, list(a,b,c), list(a))))
 #[1] 0

If you want to find the length of common elements,

 length(Reduce(intersect,list(a,b,c)))
 #[1] 2
like image 153
akrun Avatar answered Sep 28 '22 02:09

akrun


is.equal <- function(mylist) {

    check.eq <- sapply(mylist[-1], function(x) {x == mylist[[1]]})

    as.logical(apply(check.eq, 1, prod))                   

}

is.equal(list(c(1,2,3,4), c(1,2,5,4), c(1,1,3,4)))

[1]  TRUE FALSE FALSE  TRUE
like image 41
Davide Passaretti Avatar answered Sep 28 '22 04:09

Davide Passaretti