Site icon R-bloggers

Using dplyr::filter when the condition is a string

[This article was first published on R – Statistical Odds & Ends, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This took me a while to figure out and so I thought I would post this as future reference. Let’s say I have the mtcars data and I want to filter for just the rows with cyl == 6. I would do something like this:

library(tidyverse)
data(mtcars)
mtcars %>% filter(cyl == 6)

#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

What if I had the filter condition as a string instead? The code below doesn’t work:

filter_string <- "cyl == 6"
mtcars %>% filter(filter_string)

# Error: Problem with `filter()` input `..1`.
# x Input `..1` must be a logical vector, not a character.
#   Input `..1` is `filter_string`.
# Run `rlang::last_error()` to see where the error occurred.

This is one possible solution:

mtcars %>% filter(!! rlang::parse_expr(filter_string))

#                 mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Valiant        18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
# Merc 280       19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
# Merc 280C      17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

This can be useful if you are trying to running several different filters automatically. In the following contrived example, I want to compute the mean MPG for two different slices of the data:

filters <- c("carb == 4", "am == 1")
for (filter in filters) {
  print(paste0("Mean mpg for ",
               filter,
               ": ",
               mtcars %>% filter(!! rlang::parse_expr(filter)) %>%
                 summarize(mean_mpg = mean(mpg)) %>%
                 pull()))

# [1] "Mean mpg for carb == 4: 15.79"
# [1] "Mean mpg for am == 1: 24.3923076923077"
}

You can read about parse_expr here and about !! here. I don’t fully understand tidy evaluation at this point, but the code above should work in a wide variety of situations.

(Disclaimer: There was a reference I came across for the !! + rlang::parse_expr trick that I can’t find now. If anyone knows where it is please let me know and I’ll acknowledge it here in the references.)

To leave a comment for the author, please follow the link and comment on their blog: R – Statistical Odds & Ends.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.