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

使用R统计向量中符合固定顺序模式的重复分段长度

R语言实现模式子集长度统计方法

核心逻辑

所有子集均以固定首元素"A"开头,因此我们可以通过定位所有"A"的出现位置,通过相邻起始位置的差值计算前一个子集的长度,最后一个子集的长度由总向量长度减去最后一个"A"的索引再加1得到。

实现代码

示例验证代码

# 定义输入向量
input_vec <- c("A","A","B","A","A","B","A","B","C","D")

# 定位所有子集的起始位置(即"A"的索引)
start_pos <- which(input_vec == "A")

# 计算每个子集的长度
subset_lengths <- c(diff(start_pos), length(input_vec) - tail(start_pos, 1) + 1)

# 输出结果
print(subset_lengths)

运行结果

运行上述代码将输出预期结果:

[1] 1 2 1 2 4

通用函数封装

如果需要反复调用,可以封装为可复用函数:

count_subset_length <- function(input_vec, start_flag = "A") {
  start_pos <- which(input_vec == start_flag)
  if (length(start_pos) == 0) {
    warning("未检测到子集起始元素")
    return(numeric(0))
  }
  c(diff(start_pos), length(input_vec) - tail(start_pos, 1) + 1)
}

# 调用测试
count_subset_length(c("A","A","B","A","A","B","A","B","C","D"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:36:00