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

在函数中使用dplyr:传递变量名时出现错误

解决rstatix::t_test函数传递变量名参数的报错问题

问题背景

需要编写一个执行t检验的函数,针对多个temp_前缀的温度变量,要求函数能接收变量名参数。之前传递dataframe的版本可正常运行,但传递变量名时出现“列不存在”的错误,尝试过enquo、!!等tidyeval语法仍未解决,直接执行t检验代码则正常。

错误原因

rstatix::t_test的公式参数需要正确使用tidyeval语法解析传入的变量名。之前的尝试中,要么没有正确捕获变量,要么注入方式有误,导致函数将var_name当作字面量列名去查找,而非解析为传入的实际变量。

解决方案

方案1:保留硬编码数据集(不推荐)

如果必须在函数内固定使用df_weather,需要用enquo捕获变量名,再在公式中用!!注入到左侧:

balance_table <- function(var_name) {
  var_expr <- enquo(var_name)
  table_result <- df_weather %>%
    rstatix::t_test(!!var_expr ~ station) %>%
    rstatix::adjust_pvalue(method = "BH") %>%
    rstatix::add_significance()
  table_result
}
# 调用示例
balance_table(temp_ca)

方案2:通用版(推荐)

将数据集也作为参数传入,让函数更灵活:

balance_table <- function(df, var_name) {
  var_expr <- enquo(var_name)
  table_result <- df %>%
    rstatix::t_test(!!var_expr ~ station) %>%
    rstatix::adjust_pvalue(method = "BH") %>%
    rstatix::add_significance()
  table_result
}
# 调用示例
balance_table(df_weather, temp_ca)

补充:传递字符串变量名的情况

如果需要传递字符串形式的变量名(比如balance_table("temp_ca")),可以用sym将字符串转为符号再注入:

balance_table <- function(df, var_name) {
  var_expr <- rlang::sym(var_name)
  table_result <- df %>%
    rstatix::t_test(!!var_expr ~ station) %>%
    rstatix::adjust_pvalue(method = "BH") %>%
    rstatix::add_significance()
  table_result
}
# 调用示例
balance_table(df_weather, "temp_ca")

验证

上述修正后的代码均可正常生成平衡表,与直接执行的非函数代码结果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 02:18:08