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

如何在R中编写支持动态传入formula参数的wilcox检验模块化函数

问题原因

  • 原函数中直接写x ~ y构建公式时,R会默认在数据框中检索名为x、y的列,无法关联到你传入的函数参数
  • 调用函数时直接传入df$len这类向量不符合rstatix函数的参数逻辑,该类函数默认从传入的数据框中读取列,不需要单独传入列向量

修正方案

方案1:传入列名字符串(最稳妥,低版本R也兼容)

用reformulate()函数动态构建公式,适配传入的列名字符串:

library(rstatix)
library(dplyr)

wilcox_test2 <- function(df, resp_col, group_col){
  # 动态构建公式
  f <- reformulate(group_col, response = resp_col)
  df %>%
    group_by(dose) %>%
    wilcox_test(data = ., formula = f) %>%
    adjust_pvalue(method = "bonferroni") %>%
    add_significance("p.adj")
}

# 调用时传入列名的字符串形式即可
data("ToothGrowth")
df <- ToothGrowth
wilcox_test2(df, "len", "supp")

方案2:支持裸列名传入(和dplyr语法一致,不需要加引号)

利用tidy evaluation的卷曲运算符{{ }}直接识别传入的裸列名:

library(rstatix)
library(dplyr)

wilcox_test2 <- function(df, x, y){
  df %>%
    group_by(dose) %>%
    wilcox_test(data = ., formula = {{x}} ~ {{y}}) %>%
    adjust_pvalue(method = "bonferroni") %>%
    add_significance("p.adj")
}

# 调用时直接写列名即可,和dplyr的传参逻辑一致
data("ToothGrowth")
df <- ToothGrowth
wilcox_test2(df, len, supp)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:24:03