In R, why do wilcox.test gives different answerin case of formula and not using formula?

#running wilcox.test using formula 
r = wilcox.test(mpg ~ am, data=mtcars)
[1] 0.001871391

#running wilcox.test by variables
s= wilcox.test(mtcars$mpg, mtcars$am)
[1] 2.74978e-12

s= wilcox.test(mtcars$am, mtcars$mpg)
[1] 2.74978e-12

Why is p-value is different in these two cases?


In the formula, case one, is comparing the 'mpg' variable subsetted with the 'am' variable. In this case a vector of 19 values versus a vector of 13 values.
In the non-formula example, one is comparing the 'mpg' vector vs 'am' vector. This is two 32 values vectors.

 wilcox.test(mtcars$mpg[mtcars$am==0], mtcars$mpg[mtcars$am==1])

This will provide the same result as the formula format.

  • $\begingroup$ code gives error : Error in wilcox.test.default(mtcars[mtcars$mpg == 0], mtcats[mtcars$mpg == : 'x' must be numeric $\endgroup$ – cNinja Oct 4 '18 at 20:13
  • $\begingroup$ @cNinja, sorry slight error in formula, corrected and now provides the same answer as the formula format. $\endgroup$ – Dave2e Oct 5 '18 at 2:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.