wilcox_test returns the wrong U value for MWU

Viewed 177

when I use wilcox.test to run a Mann Whitney U non-parametric test, the W value that is returned is the larger of the two U values. That seems strange to me, as the MWU test uses the smaller of the two U values as the test statistic, so I would want to see that value to report the data. Below is an example. If I run the code in R, the W value is listed at 214.

wilcox.test(disp ~ am, data = mtcars)

But if I calculate this using another program or website (I like this calculator: https://www.socscistatistics.com/tests/mannwhitney/), I get that the two U values are 33 and 214. We then use 33 to check against the critical value and would report that value.

Is there any package that calculates the MWU in a more user-friendly way where it shows the correct/smaller U value as the test statistic? I tried rstatix's version and that does the same thing. Also, does anyone know why this would be the default behavior? It seems counterintuitive.

2 Answers

If you have your data in wide format, use wilcox.test in its two-argument format, rather than its formula format. Switching the arguments will provide the two U values.

Pivot mtcars to wide:

library(dplyr)
library(magrittr)

mtcars_wide<- mtcars %>%
  pivot_wider(names_from = "am", values_from = "disp", names_prefix = "am_")

Use the two-argument format for wilcox.test to get each U:

mtcars_wide %$% wilcox.test(am_0, am_1, data = .)$statistic # 214

mtcars_wide %$% wilcox.test(am_1, am_0, data = .)$statistic # 33

Note: It doesn't matter how you move the data to wide format - I use tidyverse packages but they're not necessary. The point is that you can get each U by swapping the column names when you run the test.

Note The wilcox.test function in the stats package does not follow the same convention as t.test and reverse the sign of the test statistic based on the sign of the grouped differences. It calculates a different test statistic estimate with the same significance level. The sign of the V test statistic will always be positive since it is the sum of the positive signed ranks.

Consider manually reordering your factor levels if you want the other number mtcars example

wilcox.test(disp ~ am, data = mtcars)


#>  Wilcoxon rank sum test with continuity correction
#> 
#> data:  disp by am
#> W = 214, p-value = 0.0005493
#> alternative hypothesis: true location shift is not equal to 0

mtcars$am <- factor(mtcars$am, levels = c(1,0))
wilcox.test(disp ~ am, data = mtcars)


#>  Wilcoxon rank sum test with continuity correction
#> 
#> data:  disp by am
#> W = 33, p-value = 0.0005493
#> alternative hypothesis: true location shift is not equal to 0
Related