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

如何实现支持自定义分隔符的R语言序列向量自动分组函数?

解决方案

可以通过识别连续数值组+分组格式化的方式实现自动化,无需手动指定每个区间。核心思路是先给连续序列分配相同的分组ID,再对每个分组生成对应的字符串,最后拼接所有结果:

a_function <- function(test_group, to_from = " to ", sep_group = "; ") {
  # 生成分组ID:连续数值归为同一组
  group_ids <- cumsum(c(1, diff(test_group) != 1))
  # 按分组处理每个序列
  group_strings <- lapply(split(test_group, group_ids), function(x) {
    if (length(x) == 1) {
      as.character(x)
    } else {
      paste(x[1], x[length(x)], sep = to_from)
    }
  })
  # 拼接所有分组字符串
  paste(unlist(group_strings), collapse = sep_group)
}

测试验证

用你的测试向量验证:

test_group <- c(2:4, 7:10, 14, 20:21)
a_function(test_group)

输出结果:

[1] "2 to 4; 7 to 10; 14; 20 to 21"

再测试任意零散序列(比如跨大范围的非连续数值):

random_seq <- c(0:5, 10, 12:15, 20:30, 50)
a_function(random_seq, to_from = "-", sep_group = ", ")

输出:

[1] "0-5, 10, 12-15, 20-30, 50"

代码逻辑说明

  • diff(test_group) != 1:找出相邻数值不连续的位置,作为分组断点
  • cumsum(c(1, ...)):根据断点生成连续的分组ID,让连续数值归为同一组
  • split(test_group, group_ids):把原向量按分组ID拆分成多个子向量
  • 对每个子向量判断长度:单元素直接转字符串,多元素取首尾用to_from连接
  • 最后用paste(..., collapse=sep_group)把所有分组结果拼接成最终字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 05:08:19