将索引添加到相等值的连续运行 [英] Add index to contiguous runs of equal values

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

问题描述

制作计数器索引的方法是否比使用循环更快?在相等值的连续运行中,索引应该相同。我发现循环非常慢,特别是当数据太大时。

Is there is a faster way to make a counter index than using a loop? Within contiguous runs 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

我效率低下的代码是:

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天全站免登陆