This looks easy enough, but I keep bumping my head.
I have the numeric vector v1
v1 <- c(1,1,3,5,7,7)
And I have a numeric vector v2. v2 is always a subset of v1.
I want to remove the all elements from v2 from v1, but only one (and exaclty one) v1 element per v2 element.
desired output
if v2 <- c(3,5)
I want to keep c(1,1,7,7)
from v1. This one is easy using v1[-match(v2, v1)]
.
if v2 <- c(1,7)
I want to keep c(1,3,5,7)
from v1. also, v1[-match(v2, v1)]
does the trick.
if v2 <- c(1,1)
I want to keep c(3,5,7,7)
from v1. Now v1[-match(v2, v1)]
returns [1] 1 3 5 7 7
.. Not what I want.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.
To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.
You can use vsetdiff
from the "vecsets" library (this will keep the duplicates as opposed to setdiff
), in the following way:
library(vecsets)
v1 <- c(1,1,3,5,7,7)
v2.1 <- c(3,5)
> vsetdiff(v1, v2.1)
[1] 1 1 7 7
v2.2 <- c(1,7)
> vsetdiff(v1, v2.2)
[1] 1 3 5 7
v2.3 <- c(1,1)
> vsetdiff(v1, v2.3)
[1] 3 5 7 7
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