两样本KS检验
计算公式
符号
| 符号 | 含义 |
|---|---|
| n1、n2 | 两组有效样本量 |
| F1、F2 | 两组经验分布函数 |
| D | 两条经验分布函数的最大垂直距离 |
| ne | 有效样本量,ne = n1n2 ÷ (n1 + n2) |
| x(i) | 合并样本排序后的第 i 个观测值 |
核心公式
公式 (1.1):K-S 统计量 D
\[
D=\sup_x\left|F_1(x)-F_2(x)\right|=\max_{1\le i\le n_1+n_2}\left|F_1\left(x_{(i)}\right)-F_2\left(x_{(i)}\right)\right|
\]
公式 (1.2):渐近双侧 p 值
\[
p\approx 2\sum_{k=1}^{\infty}(-1)^{k-1}\exp\left(-2k^2n_eD^2\right)
\]
公式 (1.3):精确检验的 p 值
\[
p_{\mathrm{exact}}=\Pr\left(D_{n_1,n_2}\ge D_{\mathrm{obs}}\right)
\]
小样本且两组观测没有并列值时,按 Smirnov 精确分布计算 p;样本较大或存在并列值时,改用 (1.2) 的渐近式。
参考文献
- Smirnov, N. (1948). Table for estimating the goodness of fit of empirical distributions. Annals of Mathematical Statistics, 19(2), 279–281.
- Massey, F. J. (1951). The Kolmogorov-Smirnov test for goodness of fit. Journal of the American Statistical Association, 46(253), 68–78.
- Conover, W. J. (1999). Practical Nonparametric Statistics (3rd ed.). Wiley.
算法参数
| 参数 | 取值 | 默认 | 影响 |
|---|---|---|---|
| 缺失处理 | 成对剔除 / 按列表剔除 | 成对剔除 | 成对剔除时每个因变量用自己的有效样本;按列表剔除时所有变量共用一批样本。 |
验证报告
数据与 R 包
提示词
以 G 为分组变量、Y 为分析变量做两独立样本 Kolmogorov-Smirnov 检验,比较两条经验分布是否相同,结果保留 10 位小数。
R 代码
options(digits = 15)
d <- read.csv("ks_2samp.csv")
x <- d$Y[d$G == "A"]
y <- d$Y[d$G == "B"]
r <- ks.test(x, y, alternative = "two.sided")
print(r, digits = 15)
cat("n", length(x), length(y), "D", r$statistic, "p", r$p.value, "\n")
cat("median", median(x), median(y), "mean", mean(x), mean(y),
"sd", sd(x), sd(y), "\n")
对比结果
| 指标 | SPSSAU | R | 差值 |
|---|---|---|---|
| 样本量 A | 40 | 40 | 0 |
| 样本量 B | 40 | 40 | 0 |
| D 值 | 0.4000000000 | 0.4000000000 | 0 |
| 精确 p 值 | 3.018184e−3 | 3.018184e−3 | 3.28e−9 |
| 中位数 A | 49.4523090000 | 49.4523090000 | 0 |
| 中位数 B | 55.7667695000 | 55.7667695000 | 0 |
| 平均值 A | 47.9300582500 | 47.9300582500 | 0 |
| 平均值 B | 56.8719871500 | 56.8719871500 | 0 |
| 标准差 A | 7.6294000272 | 7.6294000272 | 4.59e−11 |
| 标准差 B | 12.8493710697 | 12.8493710697 | 2.59e−11 |
结论:D 值、精确 p 值、两组均值、标准差与中位数均与 R 一致;本数据无结,R 的 ks.test 采用精确分布,与 SPSSAU 口径相同。
引用SPSSAU. 两样本KS检验:计算公式与参数[EB/OL]. SPSSAU算法手册, 2026-11-20. https://www.spssau.com/algorithm/general/ks_2samp.html.