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