在 R 中使用公式作为关键字参数(命名参数)和 wilcox.test

Using formula as a keyword argument (named parameter) with wilcox.test in R

为什么在 R 中将 "formula" 作为关键字参数与 wilcox.test 一起使用时会出现错误?文档说它有一个 "formula" 参数。

df = data.frame(A=rnorm(10), D=sample(c('p','q'), 10, replace=T))
wilcox.test(data=df, A~D)
wilcox.test(data=df, formula=A~D)

> df = data.frame(A=rnorm(10), D=sample(c('p','q'), 10, replace=T))
> wilcox.test(data=df, A~D)

    Wilcoxon rank sum test

data:  A by D
W = 13, p-value = 1
alternative hypothesis: true location shift is not equal to 0

> wilcox.test(data=df, formula=A~D)
Error in wilcox.test.default(data = df, formula = A ~ D) : 
  argument "x" is missing, with no default

我认为它变得很混乱,因为通用方法和公式方法对公式参数使用不同的名称,即 xformula。一般写S3方法时,方法的参数名要和泛型一致。

> args(wilcox.test)
function (x, ...) 
NULL

> args(stats:::wilcox.test.formula)
function (formula, data, subset, na.action, ...) 
NULL

您的参数顺序不正确。

> wilcox.test(formula=A~D, data=df)

    Wilcoxon rank sum test

data:  A by D
W = 13, p-value = 0.6667
alternative hypothesis: true location shift is not equal to 0

42- 指出我对公式参数的用途的理解是错误的,因为如果没有可选的数据参数,数据对象将从环境中继承。该函数选择默认方法而不是公式方法,因为它在第一个参数位置看不到公式参数。否则,参数顺序无关紧要。