I have two vectors:
a = c(1,1,2,2,3,3,4,4)
b = c(1)
I want to remove the first match of b from a. Thus, here only the first 1 is removed from a:
c = c(1,2,2,3,3,4,4)
The order of items in a is not important.
I tried this code:
a[a != b]
a[! a %in% b]
Both results are:
[1] 2 2 3 3 4 4.
All numbers of 1 are removed. However, I only want to remove the specific item in b from a.
If b = c(1, 1, 2), then I wish the result
[1] 2 3 3 4 4
a[-(1:3)]
The above code could lead to the result of [1] 2 3 3 4 4. However, I wish it could be more flexible. For example when the order of items are unknown or random:
a = c(3,4,3,1,2,2,1,4)
How can I do it using R?
vecsets package can perform standard set operations, while retaining duplicates:
vecsets::vsetdiff( c(1,1,2,2,3,3,4,4), c(1) )
## [1] 1 2 2 3 3 4 4
vecsets::vsetdiff( c(1,1,2,2,3,3,4,4), c(1,1,2) )
## [1] 2 3 3 4 4
Note that it will preserve the order of the first argument. Using your last example:
vecsets::vsetdiff( c(3,4,3,1,2,2,1,4), c(1,1,2) )
## [1] 3 4 3 2 4
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