1. 程式人生 > >r語言中如何進行兩組獨立樣本秩和檢驗

r語言中如何進行兩組獨立樣本秩和檢驗

itl ber rep dvd see 威爾 inf r語言 true

安裝所需的包

wants <- c("coin")
has   <- wants %in% rownames(installed.packages())
if(any(!has)) install.packages(wants[!has])>

一個樣本

測試

set.seed(123)
medH0 <- 30
DV    <- sample(0:100, 20, replace=TRUE)
DV    <- DV[DV != medH0]
N     <- length(DV)
(obs  <- sum(DV > medH0))
[1] 15
(pGreater <- 1-pbinom(obs-1, N, 0.5))
[1] 0.02069
(pTwoSided <- 2 * pGreater)
[1] 0.04139

威爾科克森排檢驗

IQ    <- c(99, 131, 118, 112, 128, 136, 120, 107, 134, 122)
medH0 <- 110
wilcox.test(IQ, alternative="greater", mu=medH0, conf.int=TRUE)
  1. Wilcoxon signed rank test
  2. data: IQ
  3. V = 48, p-value = 0.01855
  4. alternative hypothesis: true location is greater than 110
  5. 95 percent confidence interval:
  6. 113.5 Inf
  7. sample estimates:
  8. (pseudo)median
  9. 121

兩個獨立樣本

測試

Nj  <- c(20, 30)
DVa <- rnorm(Nj[1], mean= 95, sd=15)
DVb <- rnorm(Nj[2], mean=100, sd=15)
wIndDf <- data.frame(DV=c(DVa, DVb),
                     IV=factor(rep(1:2, Nj), labels=LETTERS[1:2]))

查看每組中低於或高於組合數據中位數的個案數。

library(coin)
median_test(DV ~ IV, distribution="exact", data=wIndDf)
  1. Exact Median Test
  2. data: DV by IV (A, B)
  3. Z = 1.143, p-value = 0.3868
  4. alternative hypothesis: true mu is not equal to 0

Wilcoxon秩和檢驗(曼 - 惠特尼檢疫)

wilcox.test(DV ~ IV, alternative="less", conf.int=TRUE, data=wIndDf)
  1. Wilcoxon rank sum test
  2. data: DV by IV
  3. W = 202, p-value = 0.02647
  4. alternative hypothesis: true location shift is less than 0
  5. 95 percent confidence interval:
  6. -Inf -1.771
  7. sample estimates:
  8. difference in location
  9. -9.761
  1. library(coin)
  2. wilcox_test(DV ~ IV, alternative="less", conf.int=TRUE,
  3. distribution="exact", data=wIndDf)
  1. Exact Wilcoxon Mann-Whitney Rank Sum Test
  2. data: DV by IV (A, B)
  3. Z = -1.941, p-value = 0.02647
  4. alternative hypothesis: true mu is less than 0
  5. 95 percent confidence interval:
  6. -Inf -1.771
  7. sample estimates:
  8. difference in location
  9. -9.761

兩個依賴樣本

測試

N      <- 20
DVpre  <- rnorm(N, mean= 95, sd=15)
DVpost <- rnorm(N, mean=100, sd=15)
wDepDf <- data.frame(id=factor(rep(1:N, times=2)),
                     DV=c(DVpre, DVpost),
                     IV=factor(rep(0:1, each=N), labels=c("pre", "post")))
medH0  <- 0
DVdiff <- aggregate(DV ~ id, FUN=diff, data=wDepDf)
(obs   <- sum(DVdiff$DV < medH0))
[1] 7
(pLess <- pbinom(obs, N, 0.5))
[1] 0.1316

排名威爾科克森檢驗

wilcoxsign_test(DV ~ IV | id, alternative="greater",
                distribution="exact", data=wDepDf)
  1. Exact Wilcoxon-Signed-Rank Test
  2. data: y by x (neg, pos)
  3. stratified by block
  4. Z = 2.128, p-value = 0.01638
  5. alternative hypothesis: true mu is greater than 0

分離(自動)加載的包

try(detach(package:coin))
try(detach(package:modeltools))
try(detach(package:survival))
try(detach(package:mvtnorm))
try(detach(package:splines))
try(detach(package:stats4))

r語言中如何進行兩組獨立樣本秩和檢驗