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

若如初见. 提交于 2019-12-02 01:03:38

问题


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.

回答1:


How about this...

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

[1] "X2329323"  "N23932"    "X93201"    "X9023111"  "O92311"    "9000F"
    "K9232932"  "X02311111" "U82832" 



回答2:


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"   


来源:https://stackoverflow.com/questions/50043291/perform-non-pairwise-all-to-all-comparisons-between-two-unordered-character-vect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!