Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all elements of a vector except one in dplyr pipeline

Tags:

r

dplyr

vector

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...
like image 325
hellter Avatar asked Jul 02 '16 15:07

hellter


1 Answers

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"
like image 182
akrun Avatar answered Oct 14 '22 08:10

akrun