Search code examples
rformulakeyword-argument

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


Why do I get an error when I use the "formula" as a keyword argument with wilcox.test in R? The docs say that it has a "formula" parameter.

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

Solution

  • Your arguments are not in the correct order.

    > 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- pointed out that I was incorrect about the purpose of formula arguments, since without the optional data argument the data objects would be inherited from the environment. The function chooses the default method instead of the formula method because it does not see a formula argument in the first argument location. Otherwise, argument order would not matter.