Wilcoxon rank sum test correct vectors order Running some Wilcoxon rank sum tests, I noticed that if I reverse the x and y vectors I get different values of the statistic. Since I have to report the value of W in the results, I would like to understand how to choose the right order of the vectors x, y. (In some cases the two vectors do not have the same length as in the example)
Here a short example code used in R
x = c(1,2,3,3,3,5,2,1)
y = c(2,4,1,1,1,2,2,1)
wilcox.test(y, x, paired = FALSE)
  output: W = 20, p-value = 0.2063
wilcox.test(x, y, paired = FALSE)
  output: W = 44, p-value = 0.2063


In R, the  Wilcoxon rank sum test statistic $W$ is calculated as the sum of ranks in the first sample minus the expected value of the rank sum of $x$ under the null ($\frac{m^2+m}{2}$, where $m$ is the sample size of $x$). Since the distribution of rank sums under the null is symmetric about it's mean, this gives equivalent inference as using the sum of ranks of the second variable as the test statistic, which you can see in the equal p-values for both your tests. (There are a few different forms of calculating the statistic for this test, and, as noted in the R help files for wilcox.test, none of these is canonical.)
Here's the math by hand for calculating $W$ the way R does for your example. First, note that $E[\text{rank}(x)] = \frac{64 + 8}{2} = 36$.




Obs
x
rank(x)
y
rank(y)




1
1
3.5
2
9


2
2
9
4
15


3
3
13
1
3.5


4
3
13
1
3.5


5
3
13
1
3.5


6
5
16
2
9


7
2
9
2
9


8
1
3.5
1
3.5




80 — 36 = 44

56 – 36 = 20




Ranking:

*

*The observations with value $1$ share the $1^{\text{st}} - 6^{\text{th}}$ ranks, so they each get the average of $1+2+3+4+5+6 = 3.5$


*For similar reasons the observations with value $2$, which share the $7^{\text{th}} - 11^{\text{th}}$ ranks, each get the average of those ranks: $9$.


*The observations with value $3$ each get average rank $13$.


*The observations with values $4$ and $5$ get ranks $15$ and $16$, respectively.
You can see how switching the order of x and y in the command would produce the two different test statistic values. Since these test statistics are deviations for the mean of the distribution of rank sums under the null hypothesis, they give the same probability of being observed, assuming the null hypothesis is true. So p-value = 0.2063 regardless of order, and your conclusions—almost certainly failing to reject the null hypothesis unless you are using a huge value of $\alpha$—are the same in either case.
