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:
I would also love to draw a Venn diagram.
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.
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.
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
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
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