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

如何在R语言中重编码列值?将三分位数分组替换为数值区间

解决方案(tidyverse 实现)

可以通过 dplyr 分组计算每组的极值,再拼接成目标格式的字符串:

library(tidyverse)

# 原始数据
dc <- data.frame(x = c(1, 2, 5, 6, 8, 9))
dc$tercile <- fabricatr::split_quantile(dc$x, 3)

# 替换 tercile 为区间字符串
dc <- dc %>%
  group_by(tercile) %>%
  mutate(tercile = str_glue("period {min(x)}-{max(x)}")) %>%
  ungroup()

# 查看结果
print(dc)

代码说明

  • group_by(tercile):按原三分位数分组,确保同一组的x值被归在一起
  • str_glue("period {min(x)}-{max(x)}"):利用每组x的最小值和最大值,拼接成指定格式的区间文本
  • ungroup():取消分组状态,避免对后续数据操作产生影响

执行后输出结果:

# A tibble: 6 × 2
      x tercile    
  <dbl> <glue>     
1     1 period 1-2
2     2 period 1-2
3     5 period 5-6
4     6 period 5-6
5     8 period 8-9
6     9 period 8-9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:07:11