将整数向量分组为连续运行 [英] Group integer vector into consecutive runs

查看:62
本文介绍了将整数向量分组为连续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个整数向量。我想确定以第一个向量为条件的第二个向量中出现的连续整数序列的间隔(该向量可以看成是一个因素,通过该因素第二个向量可以分为几类)。

I have two vectors of integer. I would like to identify the intervals of consecutive integer sequences presented in the second vector conditioned by the first vector (this vector can be seen as a factor, by which the second vector can be classified into several groups).

在这里我为我的问题提供一个假人。

Here I present a dummy for my problem.

第二个向量的一组数据(由第一个向量定义) ,整数单调增加。

The data, in one group (defined by the first vector) of the second vector, the integers monotonically increase.

my.data <- data.frame(
    V1=c(rep(1, 10), rep(2, 9), rep(3,11)), 
    V2=c(seq(2,5), seq(7,11), 13, seq(4, 9), seq(11,13), seq(1, 6), seq(101, 105))
)

我想要的内容:


  • 输出间隔的开始和结束

  • 在这里,分组第一列,第二列的开始整数,第三列的结束整数。

预期结果:

1, 2, 5 \n
1, 7, 11 \n
1, 13, 13 \n
2, 4, 9 \n
2, 11, 13 \n
3, 1, 6 \n
3, 101, 105 \n


推荐答案

以下是使用聚合...的简短答案。

Here's a brief answer using aggregate....

runs <- cumsum( c(0, diff(my.data$V2) > 1) )
aggregate(V2 ~ runs + V1, my.data, range)[,-1]


  V1 V2.1 V2.2
1  1    2    5
2  1    7   11
3  1   13   13
4  2    4    9
5  2   11   13
6  3    1    6
7  3  101  105

这篇关于将整数向量分组为连续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆