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

R中遍历向量时如何创建列 按分组生成指定分位数汇总数据框

R实现按分组计算指定分位数汇总表的方案

方法1:tidyverse实现(推荐,代码简洁易维护)

library(dplyr)
library(tidyr)

# 构造原始测试数据
df <- data.frame(
  Month = c("Jan", "Feb", "March", "April"),
  a = c(1,5,9,13),
  b = c(2,6,10,14),
  c = c(3,7,11,15),
  d = c(4,8,12,16)
)

# 定义需要计算的分位数
target_pct <- c(5,10,50,75)

# 分组计算+整理为目标结构
result <- df %>%
  group_by(Month) %>%
  reframe(
    # 对a-d列的数值计算分位数,type=2对齐Stata默认分位数计算逻辑
    value = quantile(c_across(a:d), probs = target_pct/100, na.rm = T, type = 2),
    pct = paste0("perc_", target_pct)
  ) %>%
  # 转换为宽表匹配要求的列结构
  pivot_wider(names_from = pct, values_from = value)

运行后输出的result就是符合要求的汇总数据框。

方法2:base R实现(无需加载第三方包)

# 构造原始数据同上
df <- data.frame(
  Month = c("Jan", "Feb", "March", "April"),
  a = c(1,5,9,13),
  b = c(2,6,10,14),
  c = c(3,7,11,15),
  d = c(4,8,12,16)
)
target_pct <- c(5,10,50,75)

# 按月份分组计算
result <- do.call(rbind, lapply(split(df, df$Month), function(x){
  vals <- as.numeric(x[, c("a","b","c","d")])
  pct_vals <- quantile(vals, probs = target_pct/100, na.rm = T, type = 2)
  res <- data.frame(Month = x$Month[1])
  for (i in seq_along(target_pct)) {
    res[[paste0("perc_", target_pct[i])]] <- pct_vals[i]
  }
  res
}))
rownames(result) <- NULL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:15:09