admin管理员组

文章数量:1122832

Using the argument formula explicitly (formula = some formula) in t.test is not working on most R versions from 3.6.3 (and maybe even before, not tested) up to current 4.4.2. The same happens with wilcox.test but not with lm or oneway.test.

The help page for t.test provides this example

 t.test(extra ~ group, data = sleep)

If we type

 t.test(data = sleep,  extra ~ group)

it also works, but

 t.test(data = sleep, formula = extra ~ group)

does not, producing an error that leads to think on a parsing argument issue:

Error in t.test.default(data = sleep, formula = extra ~ group) :

argument "x" is missing, with no default

Is this an expected behavior?

Using the argument formula explicitly (formula = some formula) in t.test is not working on most R versions from 3.6.3 (and maybe even before, not tested) up to current 4.4.2. The same happens with wilcox.test but not with lm or oneway.test.

The help page for t.test provides this example

 t.test(extra ~ group, data = sleep)

If we type

 t.test(data = sleep,  extra ~ group)

it also works, but

 t.test(data = sleep, formula = extra ~ group)

does not, producing an error that leads to think on a parsing argument issue:

Error in t.test.default(data = sleep, formula = extra ~ group) :

argument "x" is missing, with no default

Is this an expected behavior?

Share Improve this question asked Nov 22, 2024 at 22:08 JMNunesJMNunes 531 silver badge3 bronze badges 2
  • 2 This is an issue with generic methods. lm and oneway.test are not generic methods. They are simply functions. Note that the generic method has to match the specific method to be called using the FIRST argument passed. – Onyambu Commented Nov 22, 2024 at 22:27
  • This is already on R's bugzilla. – jay.sf Commented Nov 23, 2024 at 10:13
Add a comment  | 

1 Answer 1

Reset to default 4

This is arguably an R bug, or at least an "infelicity".

t.test is a generic function:

> stats::t.test
function (x, ...) 
UseMethod("t.test")

From Wickham's Advanced R section 13.4:

Method dispatch is performed by UseMethod(), which every generic calls. UseMethod() takes two arguments: the name of the generic function (required), and the argument to use for method dispatch (optional). If you omit the second argument, it will dispatch based on the first argument, which is almost always what is desired.

(emphasis added)

So, what happens when you call t.test(data = sleep, formula = extra ~ group) ? The generic function looks at its first argument, which is a data frame, so it dispatches to t.test.default() (the only other option is t.test.formula: see methods("t.test"). That function (args(stats:::t.test.default)) is expecting an argument named x and can't find it ... (it throws an error the first time the value of x is evaluated)

本文标签: Use of named argument in R function ttest (and some others)Stack Overflow