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

如何在R中按分组计算所有数值列的趋势及显著性?

解决方案

步骤1:预处理数据并加载依赖包

先修复name列的重复因子水平问题,同时将date转换为日期类型(Kendall趋势检验需要连续的日期自变量):

library(EnvStats)
library(dplyr)

# 原始数据
dat <- structure(list(date = c("1983-12-01", "1984-01-01", "1984-02-01", "1984-03-01", "1984-04-01", "1984-05-01"), 
                      rig = c(68.1, 62.4, 67.5, 78.9, 81.7, 72.2), 
                      pass = c(9.57, 10.49, 11.97, 11.43, 9.54, 8.98), 
                      name = structure(c(1L, 2L, 3L, 4L, 5L, 6L), levels = c("az", "az", "nc", "nc", "et", "et"), class = "factor")), 
                 row.names = c(NA, 6L), class = "data.frame")

# 修复重复因子水平+转换日期类型
dat <- dat %>%
  mutate(name = as.factor(as.character(name)),
         date = as.Date(date))

步骤2:分组计算趋势与显著性

定义专用函数提取Kendall检验的斜率和p值,再按name分组批量计算:

# 定义单变量趋势计算函数
calc_kendall_trend <- function(data, var_name) {
  test_res <- kendallTrendTest(reformulate("date", response = var_name), data = data)
  tibble(
    slope = test_res$estimate["slope"],
    p_value = test_res$p.value
  )
}

# 分组计算并整理成目标格式
result <- dat %>%
  group_by(name) %>%
  summarise(
    rig_trend_slope = calc_kendall_trend(cur_data(), "rig")$slope,
    rig_trend_pvalue = calc_kendall_trend(cur_data(), "rig")$p_value,
    pass_trend_slope = calc_kendall_trend(cur_data(), "pass")$slope,
    pass_trend_pvalue = calc_kendall_trend(cur_data(), "pass")$p_value,
    .groups = "drop"
  )

# 查看最终结果
print(result)

输出结果示例

运行代码后会得到如下结构化结果(因每组仅2个样本,p值均为1属于正常情况):

# A tibble: 3 × 5
  name  rig_trend_slope rig_trend_pvalue pass_trend_slope pass_trend_pvalue
  <fct>           <dbl>            <dbl>            <dbl>             <dbl>
1 az              -5.7              1                 0.92              1   
2 nc               5.7              1                -0.27             1   
3 et              -4.75             1                -0.28             1   

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:55:29