Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove vector-elements from vector

Tags:

r

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.

like image 309
Wimpel Avatar asked Mar 30 '21 14:03

Wimpel


People also ask

Can we remove element from vector?

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.

How do I remove multiple elements from a vector file?

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.

How do I remove an element from a vector string?

To remove all copies of an element from a vector , you can use std::remove like this: v. erase(std::remove(v. begin(), v.


Video Answer


1 Answers

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
like image 105
David Avatar answered Sep 20 '22 17:09

David