Using dplyr::filter when the condition is a string

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.)

3 thoughts on “Using dplyr::filter when the condition is a string

  1. You can use

    mtcars %>%
    filter_(filter_string)

    Unfortunately you get a warning:
    `filter_()` is deprecated as of dplyr 0.7.0.
    Please use `filter()` instead.

    I would be happy if the function filter_() could be reactivated. Been using it alot!

    Liked by 1 person

  2. Nice! I was doing almost the same thing until I created the hacksaw package:

    library(hacksaw)
    mtcars %>%
    filter_split(
    `carb == 4` = carb == 4,
    `am == 1` = am == 1
    ) %>%
    purrr::map(summarize, mean_mpg = mean(mpg))

    $`carb == 4`
    mean_mpg
    1 15.79

    $`am == 1`
    mean_mpg
    1 24.39231

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s