Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr filter : value is contained in a vector

Tags:

Is there a straight way to filter using dplyr::filter given an specific vector?

I'm looking for something like the code below:

top.food <- c('pizza', 'bacon', 'burger')  filter(orders, dish == 'pizza' | dish == 'bacon' | dish == 'burger') 

I've chosen a character vector but it could be of any class.

I've thought about using grepl as a logical predicate grepl(dish, top.food) but it doesn't work since dish doesn't match a valid pattern (it takes just the 1st element).

Any ideas? thnx!

like image 695
Carlos Araya Avatar asked Mar 07 '16 14:03

Carlos Araya


People also ask

Does dplyr work with vectors?

dplyr ends up looking a lot cleaner than the base R code in my opinion. unfortunately it always ends up a mess with vectors.

What does dplyr filter do?

The filter() function is used to subset a data frame, retaining all rows that satisfy your conditions. To be retained, the row must produce a value of TRUE for all conditions.


1 Answers

I think you are looking for the value matching function %in%.

filter(orders, dish %in% top.food) 

Or you can switch to slice() and use match().

slice(orders, match(dish, top.food, 0L)) 

I believe that slice() is a bit faster than filter(), so that might be beneficial to you. See help(match) for all the details on value matching.

like image 106
Rich Scriven Avatar answered Oct 21 '22 17:10

Rich Scriven