Home > Net >  Safely and elegantly drop specific elements from vector
Safely and elegantly drop specific elements from vector

Time:03-05

I would like to exclude elements in a specified list from a vector, i.e. remove elements of that vector which appear in the exclusion list.

I don't know if the elements are already missing, so dropping elements via -which(v %in% excludes) as below causes the entire vector to be cleared in the case that they do not appear in that vector.

How can I do this in a safe and elegant way? Should I necessarily use a boolean (logical) mask or is there a more elegant way I am missing?

v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")

v <- v[-which(v %in% excludes)]
v
# "things" "go"     "awry" 

which(v %in% excludes)

# Here `excludes` has already been removed, so v is cleared
v <- v[-which(v %in% excludes)]
v
# character(0)

Boolean mask approach

v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")
v <- v[!v %in% excludes]
v <- v[!v %in% excludes] # perform the removal a second time
v # contains desired value
# "things" "go"     "awry"  

CodePudding user response:

If there are no duplicates, use setdiff

setdiff(v, excludes)
[1] "things" "go"     "awry"  

Or with duplicates, vsetdiff

library(vecsets)
vsetdiff(v, excludes)
  •  Tags:  
  • r
  • Related