Kenny
Kenny

Reputation: 83

Merging 2 vectors and removing all repetitions

Say there is a vector:

v1 <- c("ab", "bc", "cd", "ef", "yolo", "da", "sm", "ez-de") 
v2 <- c("ab", "bc", "cd", "ef", "yolo-da", "sm", "ez", "de")

How do you merge the two vectors above so that we get the following?

c("ab", "bc", "cd", "ef", "yolo-da", "sm", "ez-de") 

Note that the two vectors above have the same length..

Upvotes: 8

Views: 6275

Answers (3)

Marcio Rodrigues
Marcio Rodrigues

Reputation: 339

My aproach:

library(dplyr)

a=c("ab", "bc", "cd", "ef", "yolo", "da", "sm", "ez-de") 
b=c("ab", "bc", "cd", "ef", "yolo-da", "sm", "ez", "de")

ab <- c(a,b)
ab_unique <- unique(ab)

ab
ab_unique

Upvotes: 2

joel.wilson
joel.wilson

Reputation: 8413

a stepwise approach to the solution; steps can be reduced once understood

# case 1. 
a=c("ab", "bc", "cd", "ef", "yolo", "da", "sm", "ez-de") 
b=c("ab", "bc", "cd", "ef", "yolo-da", "sm", "ez", "de")
# [1] "ab"      "bc"      "cd"      "ef"      "sm"      "yolo-da" "ez-de" 

# case 2.
a = c("lol", "it","is", "now", " jab-time")
b = c("lol", "it-is", " now", "jab", " time")
# [1] "lol"      "now"      "it-is"    "jab-time"

a = trimws(a)  # since observed that case 2 . "now" had whitespaces
b = trimws(b)  # these 2 steps are unnecessary, just check if that was a typo

c = intersect(a, b)  # extract the common values from both vectors
a = a[!(a %in% c)]   # keep only those which are not there in c
b = b[!(b %in% c)]   # keep only those which are not there in c

d = grep("-", c(a, b), value = TRUE)  # this returns only those having "-" in it

ans <- c(c , d)   

Upvotes: 2

Sandipan Dey
Sandipan Dey

Reputation: 23101

If order of the values is not a concern, we may try this:

v <- union(v1, v2)
Filter(function(x) length(grep(x, v))==1, v)
# [1] "ab"      "bc"      "cd"      "ef"      "sm"      "ez-de"   "yolo-da"

Upvotes: 3

Related Questions