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

R语言数据处理:如何提取目标值所属的连续前置序列?

R语言提取包含指定值的连续递增序列

原始数据

df <- data.frame(
  ID = 1:20,
  Value = c(2, 3, 4, 5, 1, 1, 1, 1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3)
)

需求说明

提取Value列中包含5或7的连续递增1的序列(即序列内每个值比前一个大1),并保留该序列的所有前置连续值,最终输出需匹配示例格式。

解决方案

方法1:使用dplyr包

library(dplyr)

result <- df %>%
  # 生成连续递增序列的分组标识
  mutate(group = cumsum(c(TRUE, diff(Value) != 1))) %>%
  group_by(group) %>%
  # 筛选包含目标值且严格连续递增的组
  filter(any(Value %in% c(5,7)) & all(diff(Value) == 1)) %>%
  ungroup() %>%
  select(-group)

print(result)

方法2:基础R实现

# 生成分组标识
df$group <- cumsum(c(TRUE, diff(df$Value) != 1))

# 按分组拆分并筛选符合条件的序列
selected_groups <- Filter(function(x) {
  any(x$Value %in% c(5,7)) && all(diff(x$Value) == 1)
}, split(df, df$group))

# 合并结果并清理
result <- do.call(rbind, selected_groups)
result$group <- NULL
rownames(result) <- NULL

print(result)

输出结果

ID Value
1   1     2
2   2     3
3   3     4
4   4     5
5  11     1
6  12     2
7  13     3
8  14     4
9  15     5
10 16     6
11 17     7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:27:25