You need to enable JavaScript to run this app. 按分组与季节执行pairwise ks检验 基于dplyr获取D值与p值
优惠活动
大模型
产品
解决方案
定价
更多

按分组与季节执行pairwise ks检验 基于dplyr获取D值与p值

R实现按多分组批量KS检验并输出D值、p值矩阵

通过dplyr做数据处理、purrr批量调用ks.test、tidyr做长宽格式转换,无需依赖第三方小众检验包,可同时输出D值和p值矩阵,步骤如下:

1. 加载依赖包

library(dplyr)
library(tidyr)
library(purrr)
library(tibble)

2. 数据预处理

# 构造示例数据,修正输入笔误GGI为GII
df <- tribble(
  ~season, ~Tvalues, ~LCZ, ~gr,
  "Fall", 44.61303, "F", "ROI",
  "Fall", 44.62756, "F", "ROI",
  "Fall", 44.63439, "F", "ROI",
  "Fall", 44.71301, "C", "ROI",
  "Fall", 44.59594, "C", "ROI",
  "Fall", 44.16783, "F", "GII",
  "Fall", 43.42613, "F", "GII",
  "Fall", 43.56969, "F", "GII",
  "Fall", 44.49767, "B", "GII",
  "Fall", 44.81384, "B", "GII",
  "Fall", 44.72411, "F", "ROI",
  "Fall", 44.63097, "B", "ROI",
  "Spri", 44.49938, "B", "ROI",
  "Spri", 44.41650, "B", "ROI",
  "Spri", 44.57543, "B", "ROI"
)

# 生成符合要求的分组标签,格式为LCZ_gr_season
df <- df %>% mutate(group_label = paste(LCZ, gr, season, sep = "_"))

3. 批量执行两两KS检验

# 提取所有唯一分组
all_groups <- unique(df$group_label)

# 生成两两不重复组合,批量计算KS检验结果
ks_res <- combn(all_groups, 2, simplify = FALSE) %>%
  map_dfr(function(pair){
    g1 <- pair[1]
    g2 <- pair[2]
    t1 <- df %>% filter(group_label == g1) %>% pull(Tvalues)
    t2 <- df %>% filter(group_label == g2) %>% pull(Tvalues)
    test <- ks.test(t1, t2)
    return(tibble(group1 = g1, group2 = g2, D = test$statistic, p_value = test$p.value))
  })

# 补全矩阵对称值和对角线值,方便后续转成标准矩阵
ks_res_full <- bind_rows(
  ks_res,
  ks_res %>% rename(group1 = group2, group2 = group1),
  tibble(group1 = all_groups, group2 = all_groups, D = 0, p_value = 1)
)

4. 转换为矩阵格式

# 生成D值矩阵
d_matrix <- ks_res_full %>%
  select(group1, group2, D) %>%
  pivot_wider(names_from = group2, values_from = D) %>%
  column_to_rownames("group1") %>%
  as.matrix()

# 生成p值矩阵
p_matrix <- ks_res_full %>%
  select(group1, group2, p_value) %>%
  pivot_wider(names_from = group2, values_from = p_value) %>%
  column_to_rownames("group1") %>%
  as.matrix()

  • 如果需要导出结果到本地,可直接调用write.csv(d_matrix, "D值矩阵.csv")、write.csv(p_matrix, "p值矩阵.csv")实现
  • 若分组样本量小于5时ks.test会弹出警告,属于检验本身的规则提示,可在ks.test外层加suppressWarnings()屏蔽

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 23:21:03