Add non-duplicates to vector in R

Viewed 46

I'd like to check over vectors whether there are duplicates and only get the non-duplicates in a new vector in R.

Example: I've got four vectors to start with, let's say:

vec1<-c("C1")
vec2<-c("C1", "C4")
vec3<-c("C1", "C3")
vec4<-c("C2", "C3")

I want to check whether vec1 and vec2 combined have the same elements as vec3 and vec4 combined. The ones that are different from the ones in vec3 and vec4 I want to add to a new vector (in this case that would be only variable "C4").

The same I want to for vec3 and vec4: the ones that are not in vec1 and vec2 I want to put in a new vector (in this case that would be variable "C2" and "C3").

Desired output:

vecnew1<-c("C4")
vecnew2<-c("C2, "C3")

Can I use dplyr or pipes for this?

1 Answers

Not dplyr, but probably the simplest is to use setdiff:

setdiff(c(vec1, vec2), c(vec3, vec4))
#[1] "C4"

setdiff(c(vec3, vec4), c(vec1, vec2))
#[1] "C3" "C2"

With pipes, that could work:

c(vec1, vec2) |>
  setdiff(c(vec3, vec4))
#[1] "C4"
Related