在连续运行的值中创建计数器 [英] Create counter within consecutive runs of values

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

问题描述

我希望在每次运行的相等值中创建一个序列号,例如出现次数的计数器,一旦当前行中的值与前一行中的值不同,它就会重新启动.

I wish to create a sequential number within each run of equal values, like a counter of occurrences, which restarts once the value in the current row is different from the previous row.

请在下面找到输入和预期输出的示例.

Please find an example of input and expected output below.

dataset <- data.frame(input = c("a","b","b","a","a","c","a","a","a","a","b","c"))
dataset$counter <- c(1,1,2,1,2,1,1,2,3,4,1,1)
dataset

#    input counter
# 1      a       1
# 2      b       1
# 3      b       2
# 4      a       1
# 5      a       2
# 6      c       1
# 7      a       1
# 8      a       2
# 9      a       3
# 10     a       4
# 11     b       1
# 12     c       1

<小时>

我的问题与这个问题非常相似:值出现的累积序列.

推荐答案

需要使用sequencerle:

> sequence(rle(as.character(dataset$input))$lengths)
 [1] 1 1 2 1 2 1 1 2 3 4 1 1

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

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