2

Say I have the following data frame:

df <- data.frame(a = 3:7, b = 1:5)

#   a b
# 1 3 1
# 2 4 2
# 3 5 3
# 4 6 4
# 5 7 5

I can use quasiquotation to select a column in my data frame like this:

MyVarName <- "b"
df %>% select(!!MyVarName)   

#   b
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5

Cool stuff. Now, say I want to filter using quasiquotation, like this:

df %>% filter(!!MyVarName > 3)

My aim was to produce the following:

#   a b
# 1 6 4
# 2 7 5

like I'd get from df %>% filter(b > 3), but instead I got,

#   a b
# 1 3 1
# 2 4 2
# 3 5 3
# 4 6 4
# 5 7 5

Even adding brackets (i.e., df %>% filter((!!MyVarName) > 3)) didn't help. Is it possible to use quasiquotation in filter in a similar way to this? If so, how is the syntax I used incorrect?

Dan
  • 11,370
  • 4
  • 43
  • 68
  • 3
    Are you trying to use strings? quasinotation assumes you have symbols or names. Use `MyVarName <- rlang::expr(b)` or `MyVarName <- rlang::sym("b")`. `select()` is an exception to many of the other functions because it always accepted strings and symbols. Both `df %>% select("b")` and `df %>% select(b)` would work, but that's not the case for most other dplyr functions. – MrFlick Aug 13 '18 at 17:26
  • Are you trying to use this within a function, such as where `myVarName` would be a string or a bare column name passed in as an argument? – camille Aug 13 '18 at 17:29
  • Ah, I see. Yes, I'm trying to use this in a function exactly as you say. I guess it's a dupe then... – Dan Aug 13 '18 at 17:31

0 Answers0