1

I'm trying to use objects for the column name and variables in dplyr filter? I've read a few posts, but can't get any of them to work (How do you rename a column with dplyr using a character object). It works if I name the column and variables, but not if I preassign them, as below. I want to be able to dynamically name the column and variables.

col <- "Species"
vars <- c("setosa", "versicolor")

r <- iris %>%
  filter(col %in% vars)

r <- iris %>%
  filter(Species %in% c("setosa", "versicolor"))
Mike
  • 921
  • 7
  • 26
  • Sorry, it worked, then stopped working so I was checking and it was my mistake. Works perfectly, thanks! – Mike Sep 04 '21 at 19:28

2 Answers2

1

We can use across or if_all/if_any (it doesn't matter as there is only a single column though)

library(dplyr)
out <- iris %>%
   filter(across(all_of(col), ~ . %in% vars))

-checking

> unique(out$Species)
[1] setosa     versicolor
Levels: setosa versicolor virginica

Or another option is to convert to symbol and evaluate (!!)

out2 <- iris %>%
   filter(!! rlang::sym(col) %in% vars)

-checking

> identical(out, out2)
[1] TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Couple of other options -

#1. Use `.data` - 

library(dplyr)
iris %>% filter(.data[[col]] %in% vars)

#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#1            5.1         3.5          1.4         0.2     setosa
#2            4.9         3.0          1.4         0.2     setosa
#3            4.7         3.2          1.3         0.2     setosa
#4            4.6         3.1          1.5         0.2     setosa
#5            5.0         3.6          1.4         0.2     setosa
#...
#...

#2. In base R - 

iris[iris[[col]] %in% vars, ]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213