Add index to contiguous runs of equal values

岁酱吖の 提交于 2019-11-26 19:05:45

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
Arun

Using data.table, which has the function rleid():

require(data.table) # v1.9.5+
rleid(x)
#  [1] 1 2 3 4 5 5 6 7 7 8 8 8 9

This will work with numeric of character values:

rep(1:length(rle(x)$values), times = rle(x)$lengths)
#[1] 1 2 3 4 5 5 6 7 7 8 8 8 9

You can also be a bit more efficient by calling rle just once (about 2x faster) and a very slight speed improvement can be made using rep.int instead of rep:

y <- rle(x)
rep.int(1:length(y$values), times = y$lengths)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!