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

在R中按Student分组计算指定百分位数的实现方法咨询

按分组计算自定义百分位数的简单方法

如果你已经在用mosaic包的favstats,直接修改它的quantiles参数就能输出自定义百分位数,完全贴合你现有的操作习惯:

library(mosaic)

# 指定需要的百分位数(比如5%、15%、50%、90%)
favstats(salary ~ student, data = Default, na.rm = TRUE, 
         quantiles = c(0.05, 0.15, 0.5, 0.9))

如果想试试更灵活的方法,推荐用dplyr(属于tidyverse工具集,代码逻辑清晰,新手友好):

# 首次使用先安装dplyr
# install.packages("dplyr")
library(dplyr)

# 按student分组,计算指定百分位数
Default %>%
  group_by(student) %>%
  summarize(
    第5百分位 = quantile(salary, probs = 0.05, na.rm = TRUE),
    第15百分位 = quantile(salary, probs = 0.15, na.rm = TRUE),
    中位数 = quantile(salary, probs = 0.5, na.rm = TRUE)
  )

要是不想装额外包,用base R原生的aggregate函数也能搞定:

# base R原生方法,无需额外安装包
aggregate(
  salary ~ student, 
  data = Default, 
  FUN = function(x) quantile(x, probs = c(0.05, 0.15), na.rm = TRUE)
)

三个方法里,favstats改参数是最快的方案,dplyr则更适合后续做更多数据处理的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:25:24