为相等值的连续运行创建组号 [英] Create group number for contiguous runs of equal values

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

问题描述

是否有比使用循环更快的方法来创建计数器索引?对于每个连续的相等值,索引应相同.我发现循环非常慢,尤其是在数据很大的情况下.

Is there is a faster way to make a counter index than using a loop? For each contiguous run of equal values, the index should be the same. I find the looping very slow especially when the data is so big.

为说明起见,这是输入和所需的输出

For illustration, here is the input and desired output

x <- c(2, 3, 9, 2, 4, 4, 3, 4, 4, 5, 5, 5, 1)

所需的结果计数器:

c(1, 2, 3, 4, 5, 5, 6, 7, 7, 8, 8, 8, 9)

请注意,连续的运行具有不同索引.例如.查看值 2 4

Note that non-contiguous runs have different indexes. E.g. see the desired indexes of the values 2 and 4

我效率低下的代码是这样的:

My inefficient code is this:

group[1]<-1
counter<-1
for (i in 2:n){
if (x[i]==x[i-1]){
    group[i]<-counter
}else{
    counter<-counter+1
    group[1]<-counter}
}

推荐答案

如果具有这样的数值,则可以使用 diff cumsum 在值

If you have numeric values like this, you can use diff and cumsum to add up changes in values

x <- c(2,3,9,2,4,4,3,4,4,5,5,5,1)
cumsum(c(1,diff(x)!=0))
# [1] 1 2 3 4 5 5 6 7 7 8 8 8 9

这篇关于为相等值的连续运行创建组号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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