Wilcoxon signed-rank test using R

• 背景：Wilcoxon signed-rank test是用来检验两个数组是否来自同一分布的

n = 1000
x <- rnorm(n,0,1)
y <- rnorm(n,0,5)
# x和y是要检验的变量

df <- data.frame(x, y)
# alpha是置信水平参数
Wil_test <- function(dataframe_or_x, y = 1, alpha = 0.05){
if(is.data.frame(dataframe_or_x)){
x = dataframe_or_x['x']
y = dataframe_or_x['y']
}
else {
x = dataframe_or_x
}
d <-  x - y
d <- d[d != 0]
n = length(d)
d_absolute = abs(d)
r = rank(d_absolute, na.last = TRUE,
ties.method ="average")
SR_plus = sum(r[d > 0])
SR_minus = sum(r[d < 0])
t = min(SR_plus, SR_minus)
E_t = n * (n + 1)/4
Var_t = n * (n + 1) *(2*n + 1) / 24
z = (t - E_t) / sqrt(Var_t)
if(abs(z) > qnorm(1 - alpha/2)){
print("NUll hypothesis rejected.")
}
else {
print("NUll hypothesis not rejected.")
}
p <- 2 * (1 - pnorm(abs(z)))
return(p)
}
# when x and y are both provided
Wil_test(x, y)
## [1] "NUll hypothesis not rejected."
## [1] 0.8835577
# when a dataframe is provided
Wil_test(df)
## [1] "NUll hypothesis not rejected."
## [1] 0.8835577


• 当然，也可以用stats包来完成这一任务

library(stats)

wilcox.test(x, y)