为连续运行的值创建索引 [英] Create index for contiguous runs of values

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

问题描述

我有一个向量:

test <-c(1,1,0,2,2,3,4,1,1,0)  
test  
# [1] 1 1 0 2 2 3 4 1 1 0

我想构造一个分组变量来指示值何时发生变化:

I want to construct an grouping variable which indicates when values change:

# [1] 1 1 2 3 3 4 5 6 6 7

最好的方法是什么?

推荐答案

使用游程长度编码 (rle)、seq_alongrep

Use run length encoding (rle), seq_along and rep

r <- rle(test)

changes <- rep(seq_along(r$lengths), r$lengths)
changes
## [1] 1 1 2 3 3 4 5 6 6 7

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

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