# wilcox.test gives different results in when using formula

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)
print(r$p.value) [1] 0.001871391 #running wilcox.test by variables s= wilcox.test(mtcars$mpg, mtcars$am) print(s$p.value)
[1] 2.74978e-12

s= wilcox.test(mtcars$am, mtcars$mpg)
print(s$p.value) [1] 2.74978e-12  Why is p-value is different in these two cases? ## 1 Answer 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. • code gives error : Error in wilcox.test.default(mtcars[mtcars$mpg == 0], mtcats[mtcars\$mpg == : 'x' must be numeric – cNinja Oct 4 '18 at 20:13
• @cNinja, sorry slight error in formula, corrected and now provides the same answer as the formula format. – Dave2e Oct 5 '18 at 2:43