dplyr中quo()的逆操作疑问:!!quo(1)为何无法正常运行?
Let's break down your questions clearly—tidy eval can feel a bit opaque at first, so it's totally reasonable to hit these roadblocks!
Why does !!quo(1) fail?
The !! (unquote) operator isn't a native base R feature—it's part of the tidy evaluation framework powering dplyr and other tidyverse packages. When you run !!quo(1) directly in the global environment, R has no context to recognize !! as a tidy eval tool, so it throws a syntax error.
The !! operator only works inside functions built to parse tidy eval syntax (like dplyr's mutate(), filter(), or select()). These functions use rlang under the hood to interpret !! as a signal to "unquote" the quosure and insert its actual value into the expression being evaluated.
What's the tidyverse equivalent of base R's eval(quote(1))?
For evaluating quosures directly (outside of dplyr verbs), use rlang::eval_tidy(). This function is purpose-built to handle quosures (expressions tied to a specific environment) and behaves like base R's eval() but respects the environment stored in the quosure.
Example usage:
library(rlang) eval_tidy(quo(1)) # Returns 1, just like eval(quote(1))
If your quosure references variables from a specific environment, eval_tidy() will correctly resolve those variables using the quosure's attached environment—something base R's eval() might handle less reliably in edge cases. For example:
my_env <- rlang::env(a = 5) my_quosure <- rlang::quo(a + 3) rlang::env_bind(my_quosure, .env = my_env) eval_tidy(my_quosure) # Returns 8, using the quosure's stored environment eval(my_quosure) # Also returns 8 here, but eval_tidy is safer for quosure-specific workflows
Does !! only work inside dplyr functions?
More precisely: !! works inside any function that supports tidy evaluation. This includes:
- Most dplyr verbs (
mutate(),filter(),summarize(), etc.) - rlang functions like
expr()(for building expressions programmatically) - Custom functions you write using rlang tools like
enquo()orensym()to capture user inputs as quosures
Here's a quick example of a custom function using !!:
library(rlang) print_quo_value <- function(input_quosure) { cat("The value is:", !!input_quosure, "\n") } print_quo_value(quo(42)) # Prints: The value is: 42
In base R functions or the global environment, !! has no special meaning and will trigger a syntax error, as you experienced.
内容的提问来源于stack exchange,提问作者sirallen

