Perform non-pairwise all-to-all comparisons between two unordered character vectors --- The opposite of intersect --- all-to-all setdiff
Asked Answered
S

2

5

EXAMPLE DATA

v1 <- c("E82391", "X2329323", "C239923", "E1211", "N23932", "F93249232", "X93201", "X9023111", "O92311", "9000F", "K9232932", "L9232932", "X02311111")
v2 <- c("L9232932", "C239923", "E1211", "E82391", "F93249232", "U82832")

PROBLEM

I want to extract only those items that are in one of the vectors and not in the other.

I understand that setdiff is unable to compare two unordered character vectors and find all the differences between the two..

Does, for example, %in% perform all-to-all comparisons between two character vectors?

In this case, it does work (although it does not report those elements that are in v2 and not in v1).

> v1[!v1 %in% v2]
[1] "X2329323"  "N23932"    "X93201"    "X9023111"  "O92311"    "9000F"     "K9232932"  "X02311111"

Another way is using a user-defined function named outersect as shown here which shows all the differences.

outersect <- function(x, y) {
  sort(c(x[!x%in%y],
         y[!y%in%x]))
}

outersect(v1,v2)

QUESTION

I am really interested to know whether there are any R functions that would easily perform all-to-all comparisons between two character vectors! The idea is to really improve the readability of the code (specially when there are dozens of vectors that need to be compared to each other).

What is the safest and most efficient way to perform such all-to-all comparisons? More specifically, is there a function in R that would

References.

  1. Breyal, Tony. "outersect(): The opposite of R’s intersect() function", Nov. 2011. R-bloggers.
Sheepdog answered 26/4, 2018 at 12:42 Comment(1)
I would say c(v1[!v1 %in% v2], v2[!v2 %in% v1] ) Danseuse
Z
0

How about this...

setdiff(union(v1,v2),intersect(v1,v2))

[1] "X2329323"  "N23932"    "X93201"    "X9023111"  "O92311"    "9000F"
    "K9232932"  "X02311111" "U82832" 
Zilpah answered 26/4, 2018 at 12:47 Comment(0)
E
0

Maybe this:

both <- c(unique(v1),unique(v2))
both[! (duplicated(both) | duplicated(both, fromLast = T))]
[1] "X2329323"  "N23932"    "X93201"    "X9023111"  "O92311"    "9000F"     "K9232932"  "X02311111" "U82832"   
Epithelioma answered 26/4, 2018 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.