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

如何基于分位数参考表为R数据框新增考试成绩对应分位列

R实现分位数匹配方案

你可以用tidyverse套件的dplyr和tidyr工具完成需求,注意quantile是R内置函数名,建议参考表重命名为quantile_ref避免冲突,完整代码如下:

# 加载依赖
library(tidyverse)

# 构造模拟数据
df <- data.frame(
  "Name" = c("John", "Mary", "Emily"), 
  "Grade" = c("8","9","10"), 
  "Test Score" = c(5,61,60)
)

quantile_ref <- data.frame(
  "Grade" = c("8","9","10"), 
  "Quantile 1" = c(10,15,20), 
  "Quantile 2" = c(50,60,70),
  "Quantile 3" = c(60,80,100)
)

# 核心处理逻辑
result <- df %>%
  # 关联长格式的分位数参考表
  left_join(
    quantile_ref %>%
      # 宽表转长表,得到每个年级各分位数对应的截断值
      pivot_longer(cols = -Grade, names_to = "Quantile", values_to = "cutoff"),
    by = "Grade"
  ) %>%
  # 按每个学生分组
  group_by(Name, Grade, `Test Score`) %>%
  # 筛选第一个大于等于考试分数的截断值对应的分位数
  arrange(cutoff) %>%
  filter(cutoff >= `Test Score`) %>%
  slice_head(n = 1) %>%
  ungroup() %>%
  # 保留需要的列
  select(Name, Grade, `Test Score`, Quantile)

# 输出结果
print(result)

运行上述代码得到的结果和你期望的完全一致:

# A tibble: 3 × 4
  Name  Grade `Test Score` Quantile  
  <chr> <chr>        <dbl> <chr>     
1 John  8                5 Quantile 1
2 Mary  9               61 Quantile 3
3 Emily 10              60 Quantile 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:36:04