r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
508 stars 138 forks source link

Invalid formula when using !! on right hand side of formula #606

Closed NikNakk closed 6 years ago

NikNakk commented 6 years ago

I've run into an issue with unquoting a quosure on the right-hand-side of a formula. Is this known? Is there a workaround?

library(rlang)
x <- sample(LETTERS[1:2], 100, replace = TRUE)
y <- 1:100
xq <- quo(x)
yq <- quo(y)
wilcox.test(y ~ x) # works
eval_tidy(quo(wilcox.test(y ~ x))) # works
eval_tidy(quo(wilcox.test(!!yq ~ x))) # works
eval_tidy(quo(wilcox.test(y ~ !!xq))) # fails with error 'invalid model formula'
yutannihilation commented 6 years ago

In formula, you have to use symbols, not quosures. If you investigate the unquoted expression with expr(), you'll find the formulas have extra ~.

library(rlang)

xq <- quo(x)
yq <- quo(y)

expr(
  eval_tidy(quo(wilcox.test(!!yq ~ x)))
)
#> eval_tidy(quo(wilcox.test(~y ~ x)))

expr(
  eval_tidy(quo(wilcox.test(y ~ !!xq)))
)
#> eval_tidy(quo(wilcox.test(y ~ ~x)))

In this case, I think you can use expr() instead of quo() to get symbols.

xq <- expr(x)
yq <- expr(y)
lionel- commented 6 years ago

Thanks @yutannihilation. As a general rule it's better to use expr() and only create quosures with enquo(), i.e. for stuff that doesn't belong to you. That's the approach we are taking in https://tidyeval.tidyverse.org which will replace the dplyr vignette.