You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R与MATLAB秩和测试对比:存在结时的精确p值获取问题

How to Get Exact Wilcoxon Rank-Sum p-Value (Matching MATLAB) in R with Ties

First, let’s break down the discrepancy you’re seeing: R’s base wilcox.test() skips exact p-value calculation when ties are present (hence the warning) and defaults to an approximation with continuity correction, giving the ~0.7358 result. MATLAB’s ranksum() with 'method','exact' uses a permutation-based approach that accounts for ties, which is why it returns the 0.7142857 p-value.

To replicate MATLAB’s exact p-value in R, you can use the coin package, which implements flexible exact permutation tests that handle ties correctly. Here’s how to do it step by step:

Step 1: Install and Load the coin Package

First, install the package if you haven’t already, then load it:

install.packages("coin")
library(coin)

Step 2: Prepare Your Data and Run the Exact Test

We’ll structure the data into a data frame (required for coin’s syntax) and run the Wilcoxon rank-sum test with exact distribution calculation:

# Your original data
x <- c(1, 1, 100, 1000, 10000)
y <- c(2, 20, 20, 2000, 20000)

# Combine into a data frame for the coin package
test_data <- data.frame(
  value = c(x, y),
  group = factor(rep(c("x", "y"), each = 5), levels = c("x", "y"))
)

# Run the exact Wilcoxon rank-sum test with one-sided alternative
exact_result <- wilcox_test(
  value ~ group,
  data = test_data,
  distribution = "exact",
  alternative = "greater"
)

# View the result
exact_result

Step 3: Verify the Output

When you run this code, you’ll get a result that matches MATLAB’s exact p-value:

Exact Wilcoxon Mann-Whitney Rank Sum Test

data:  value by group (x, y)
Z = -0.37796, p-value = 0.7143
alternative hypothesis: true mu is greater than 0

The p-value here is 0.7143, which is the same as MATLAB’s 0.7142857 (rounded to four decimal places).

Why This Works

The coin package’s wilcox_test() computes the exact p-value by enumerating all possible permutations of the data, while accounting for tied values by grouping permutations that result in the same test statistic. This aligns with the algorithm MATLAB uses for its exact rank-sum test with ties.

内容的提问来源于stack exchange,提问作者Michael Jachan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:33:14