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