tidy evaluation:运行自定义函数时出现无效参数错误求助
Let's break down what's happening with your code and how to fix it.
The Root Issue
Your function intends to use the n = 10 defined inside my_mutate, but when you capture the expression x+n with enquo(var), it retains the context of the calling environment (the global environment where n = 100 is defined). This mismatch can lead to unexpected behavior, and in some cases (depending on your tidyverse version or setup), an invalid argument error if the expression can't resolve correctly.
Fix 1: Force the Expression to Use the Function's Internal Environment
If you want x+n to reference the n = 10 inside your function, adjust the environment of the captured quosure using quo_set_env():
library(tidyverse) my_mutate = function(df, var){ n = 10 var = enquo(var) # Change the quosure's environment to the function's internal context var = quo_set_env(var, current_env()) mutate(df, y = !!var) } df = tibble(x = 1) n = 100 my_mutate(df, x+n) # Returns y = 1 + 10 = 11
Fix 2: Use inject() for Explicit Environment Control (dplyr 1.0.0+)
For a cleaner approach (available in newer dplyr versions), use inject() to evaluate the expression directly in the function's environment:
my_mutate = function(df, var){ n = 10 inject(mutate(df, y = {{var}}), env = current_env()) }
Fix 3: Explicitly Inject the Internal n into the Expression
If you only need to replace specific variables, manually inject the internal n into the captured expression:
my_mutate = function(df, var){ n = 10 var = enquo(var) # Replace references to n in the expression with our internal value var = quo(!!var %>% replace_vars(list(n = !!n))) mutate(df, y = !!var) }
Why enexpr() Didn't Work
When you used enexpr(var), you captured the raw expression x+n but didn't attach any environment context. When mutate() evaluates this expression, it still looks to the global environment for n—so you'd still get 1 + 100 instead of the intended 1 + 10, and this could trigger errors if n wasn't defined globally.
内容的提问来源于stack exchange,提问作者SarahGC

