You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让自定义dplyr函数同时支持符号与字符串参数(非标准求值)

Got it, let's work through how to make your function play nice with string variables without modifying the function itself!

The Call-Side Fix (No Function Changes Needed)

Your current function uses enquo() to capture the input as a quoted expression, which works great when you pass a symbol like y. When you have a string stored in a variable (like myVar <- "y"), you just need to convert that string to a symbol first, then inject it into the function call using the !! (bang-bang) operator from rlang.

Here's how to do it step by step:

library(dplyr)
library(rlang)

# Your original function (unchanged)
testFun <- function(data, metric) { 
  metric <- enquo(metric) 
  metric_name <- quo_name(metric) 
  data %>% mutate(!!metric_name := `-`(!!metric, first(!!metric)) / first(!!metric) * 100) 
}

# Define your string variable
myVar <- "y"
# Create your test data frame
df <- data.frame(x = c("a", "b", "c"), y = 1:3)

# The correct call for string variables
testFun(df, !!sym(myVar))

Why this works:

  • sym(myVar) converts the string "y" into a proper R symbol (same as typing y directly).
  • The !! operator "unquotes" this symbol when passing it to testFun, so enquo(metric) captures quo(y)—exactly what it gets when you pass y directly. This makes the rest of your function logic work seamlessly.

Bonus: Make the Function Support Both Symbols and Strings (Minor Tweak)

If you ever want to skip the call-side conversion entirely, you can swap enquo() with ensym() in your function. ensym() automatically handles both symbols and strings as input, so you don't need to modify how you call the function:

testFun_v2 <- function(data, metric) { 
  metric <- ensym(metric)  # Changed from enquo to ensym
  metric_name <- quo_name(metric) 
  data %>% mutate(!!metric_name := `-`(!!metric, first(!!metric)) / first(!!metric) * 100) 
}

# Both calls now work without extra steps
testFun_v2(df, y)
testFun_v2(df, myVar)

This is a small change that makes the function more flexible, but since you asked to prioritize adjusting the call method, the first solution is exactly what you need.

内容的提问来源于stack exchange,提问作者M4RT1NK4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:13:39