simplyPTA
simplyPTA

Reputation: 440

dplyr: Assign a variable a tidy-select expression for reuse

Let's say I have a lot of columns, but I usually do some calculations on a specific subset of columns:

my_df <- mtcars %>%
    filter(if_all(contains("p"), is.numeric)) %>%
    mutate(across(contains("p"), as.character))

I want to assign that tidy-select to a variable so I can use it later on, something like:

# doesn't work
my_cols <- contains("p")
my_df <- mtcars %>%
    filter(if_all(my_cols, is.numeric)) %>%
    mutate(across(my_cols, as.character))

Many thanks

Upvotes: 1

Views: 355

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35554

You could quote the tidy-select syntax and inject them with !! in the functions that support tidy selections.

my_cols <- quote(contains("Sepal"))

iris %>%
  filter(if_all(!!my_cols, `>`, 4))

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.7         4.4          1.5         0.4  setosa
2          5.2         4.1          1.5         0.1  setosa
3          5.5         4.2          1.4         0.2  setosa

Upvotes: 2

Related Questions