David
David

Reputation: 326

How to remove a single non unique element from a list or vector in r

What im looking for is a efficient way to remove a single nonunique element.

Say i have the vector:

c(1,1,1,2,2,3,3,4)

and i want to remove:

c(1,2)

such so that the result would be

c(1,1,2,3,3,4)

Im sure its very simple but im at a loss. Sound out!

Upvotes: 2

Views: 106

Answers (1)

shadow
shadow

Reputation: 22343

The function you are looking for is match. Here's the code

a <- c(1,1,1,2,2,3,3,4)
b <- c(1,2)

a[-match(b, a)]
### [1] 1 1 2 3 3 4

This works because match only returns a vector of the positions of (first) matches of its first argument in its second.

EDIT: As @Ananda Mahto pointed out, this only works if all elements in b are also in a. For a more general formula use the following function

element_rm <- function(a, b){
  if (any(b%in%a)) return(a[-match(b[b%in%a], a)])
  else return(a)
}
a <- c(1,1,1,2,2,3,3,4)
element_rm(a, c(1,2))
##  [1] 1 1 2 3 3 4
element_rm(a, c(2,5))
## [1] 1 1 1 2 3 3 4
element_rm(a, 5)
## [1] 1 1 1 2 2 3 3 4
element_rm(a, c(4,4))
## [1] 1 1 1 2 2 3 3

Upvotes: 4

Related Questions