hellter
hellter

Reputation: 1004

Select all elements of a vector except one in dplyr pipeline

I want to select all the elements of a character vector except one that matches a specific character.
I could do it easily with %in%, but I don't see how to do this inside a dplyr pipeline.

Example:
What I want

names<-c("a","b","c","d","e")
names[!names %in% "c"]
 [1] "a" "b" "d" "e"

How I want it:

names<-c("a","b","c","d","e")
names %>% ...something...

Upvotes: 7

Views: 8823

Answers (1)

akrun
akrun

Reputation: 887098

If there are no duplicates, we can use setdiff

library(magrittr)
names %>% 
     setdiff(., "c")
#[1] "a" "b" "d" "e"

Or use the magrittr operations to subset the vector.

names %>%
   `%in%`("c") %>% 
   `!` %>%
    extract(names, .)
#[1] "a" "b" "d" "e"

Upvotes: 11

Related Questions