Using R formula with dplyr

Viewed 109

I'm writing a function that takes in a formula and uses the different elements of that formula to manipulate a data frame. I'm running into trouble when I try to use dplyr (I think this is because of something called "non-standard evaluation").

For example, I want to reference a column in a data frame df using the elements in the formula. If I store the formula as form and want to access the column of df named for the first element of form I can write:

df[all.vars(form)[1]].

Unfortunately, the following doesn't work:

df %>% filter(all.vars(form)[1]) < 100).

How would I go about referencing the variable this way using dpylr? I've tried several things like rlang::sym but haven't had any luck.

1 Answers

We could use across, which can one or more columns

library(dplyr)
df %>%
    filter(across(all.vars(form), ~ . < 100))

If it is a single column

df %>% 
     filter(across(all.vars(form)[1], ~ . < 100))

Or another option is rlang::sym with !!

df %>%
     filter(!! rlang::sym(all.vars(form)[1]))

The output of all.vars is character class and we are converting to symbol and evaluating (!!)


Using a small reproducible example

data(mtcars)
form <- mpg ~ cyl
mtcars %>%
      filter(!! rlang::sym(all.vars(form)[1]) < 15)
#                      mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Duster 360          14.3   8  360 245 3.21 3.570 15.84  0  0    3    4
#Cadillac Fleetwood  10.4   8  472 205 2.93 5.250 17.98  0  0    3    4
#Lincoln Continental 10.4   8  460 215 3.00 5.424 17.82  0  0    3    4
#Chrysler Imperial   14.7   8  440 230 3.23 5.345 17.42  0  0    3    4
#Camaro Z28          13.3   8  350 245 3.73 3.840 15.41  0  0    3    4
Related