0

Suppose we have the following data frame:

df <- data.frame(x=1:10, odd=rep(c(T,F), 5))

And a variable that stores the name of the odd column:

odd_col <- 'odd'

How do I use odd_col to reference the odd column in a dplyr::filter operation?

From what I've read in the documentation on Quoting in dplyr, I would think the following would be the correct approach:

library(dplyr)

odd_col <- enquo(odd_col)

# give the rows with odd entries
filter(df, !!odd_col)

but this results in an error:

Error: Argument 2 filter condition does not evaluate to a logical vector

However, this approach seems to work just fine with other dplyr operations, for example,

pull(df, !!odd_col)
# [1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
merv
  • 67,214
  • 13
  • 180
  • 245
  • 2
    It works with pull, because pull does accept strings, i.e. `pull(df, 'odd')` works, but `filter(df, 'odd')` doesn't. So the problem is that you use enquo on a string and not the raw variable name. – kath Oct 02 '19 at 17:20

1 Answers1

1

We can use sym instead of enquo as it is a string

library(dplyr)
filter(df, !!rlang::sym(odd_col))
# x  odd
#1 1 TRUE
#2 3 TRUE
#3 5 TRUE
#4 7 TRUE
#5 9 TRUE
akrun
  • 874,273
  • 37
  • 540
  • 662