Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Safely and elegantly drop specific elements from vector

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"  

>Solution :

If there are no duplicates, use setdiff

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

Or with duplicates, vsetdiff

library(vecsets)
vsetdiff(v, excludes)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading