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..
Using std::remove function A simple solution is to iterate the vector, and for each element, we delete all its duplicates from the vector if present. We can either write our own routine for this or use the std::remove algorithm that makes our code elegant. This approach takes constant space but runs in O(n2) time.
We can combine vectors by adding them, the sum of two vectors is called the resultant. In order to add two vectors, we add the corresponding components.
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"
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)
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