Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two character vectors in R

Tags:

r

venn-diagram

I have two character vectors of IDs.

I would like to compare the two character vectors, in particular I am interested in the following figures:

  • How many IDs are both in A and B
  • How many IDs are in A but not in B
  • How many IDs are in B but not in A

I would also love to draw a Venn diagram.

like image 668
Aslan986 Avatar asked Jul 11 '13 15:07

Aslan986


People also ask

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.

How do I compare two lists of elements in R?

Compare equal elements in two R lists Third, you can also compare the equal items of two lists with %in% operator or with the compare. list function of the useful library. The result will be a logical vector.


2 Answers

Here are some basics to try out:

> A = c("Dog", "Cat", "Mouse") > B = c("Tiger","Lion","Cat") > A %in% B [1] FALSE  TRUE FALSE > intersect(A,B) [1] "Cat" > setdiff(A,B) [1] "Dog"   "Mouse" > setdiff(B,A) [1] "Tiger" "Lion"  

Similarly, you could get counts simply as:

> length(intersect(A,B)) [1] 1 > length(setdiff(A,B)) [1] 2 > length(setdiff(B,A)) [1] 2 
like image 75
Mittenchops Avatar answered Oct 04 '22 08:10

Mittenchops


I'm usually dealing with large-ish sets, so I use a table instead of a Venn diagram:

xtab_set <- function(A,B){     both    <-  union(A,B)     inA     <-  both %in% A     inB     <-  both %in% B     return(table(inA,inB)) }  set.seed(1) A <- sample(letters[1:20],10,replace=TRUE) B <- sample(letters[1:20],10,replace=TRUE) xtab_set(A,B)  #        inB # inA     FALSE TRUE #   FALSE     0    5 #   TRUE      6    3 
like image 21
Frank Avatar answered Oct 04 '22 07:10

Frank