2
votes

I am trying to generate a function that will return the test statistic of the Wilcoxon Rank Sum Test (It is for a class, I know there is a built-in function)

y=c(3,4,4,4,5,6,7)
total=c(x,y)
names=c(rep(c("X"), times = length(x)),rep(c("Y"), times = length(y)))
df=data.frame(names,total)```
df
     names total
1      X     1
2      X     2
3      X     3
4      X     4
5      X     5
6      X     6
7      X     7
8      X     8
9      X     9
10     X    10
11     Y     3
12     Y     4
13     Y     4
14     Y     5
15     Y     6
16     Y     7

Then I order as descending the "total" column and once ordered I rank them

newdf= df[order(total),]
rankdf=data.frame(newdf,rank=c(1:nrow(newdf)))
rankdf
   names total rank
1      X     1    1
2      X     2    2
3      X     3    3
11     Y     3    4
4      X     4    5
12     Y     4    6
13     Y     4    7
5      X     5    8
14     Y     5    9
6      X     6   10
15     Y     6   11
7      X     7   12
16     Y     7   13
8      X     8   14
9      X     9   15
10     X    10   16

Is there a way I can check which elements from the column "total" are identical, and calculate the mean among their corresponding values in column "rank", and reassign the result in the rows, WITHOUT losing the names column. I was expecting something like this:

  names total rank
1      X     1    1
2      X     2    2
3      X     3    3.5
11     Y     3    3.5
4      X     4    6
12     Y     4    6
13     Y     4    6
5      X     5    8.5
14     Y     5    8.5
6      X     6   10.5
15     Y     6   10.5
7      X     7   12.5
16     Y     7   12.5
8      X     8   14
9      X     9   15
10     X    10   16

I am very new to R. Thanks in advance!

Val

1

1 Answers

0
votes

In wilcox.test, the function rank is used, so you can do the same:

cbind(rankdf,w_rank=rank(rankdf$total))
   names total rank w_rank
1      X     1    1    1.0
2      X     2    2    2.0
3      X     3    3    3.5
11     Y     3    4    3.5
4      X     4    5    6.5
12     Y     4    6    6.5
13     Y     4    7    6.5
14     Y     4    8    6.5
5      X     5    9    9.5
15     Y     5   10    9.5
6      X     6   11   11.5
16     Y     6   12   11.5
7      X     7   13   13.5
17     Y     7   14   13.5
8      X     8   15   15.0
9      X     9   16   16.0
10     X    10   17   17.0