获取值运行的开始和结束索引 [英] Get start and end index of runs of values

查看:30
本文介绍了获取值运行的开始和结束索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量:

a <- c(1, 1, 0, 0, 1, 2, 0, 0)

我想获取每次运行的相等值的开始和结束索引:

I would like to get the start and end indexes of each run of equal values:

number start  end
0        3     4
0        7     8
1        1     2
1        5     5
2        6     6

推荐答案

基于 R 的解决方案.

A solution from base R.

a <- c(1,1,0,0,1,2,0,0)

# Get run length encoding
b <- rle(a)

# Create a data frame
dt <- data.frame(number = b$values, lengths = b$lengths)
# Get the end
dt$end <- cumsum(dt$lengths)
# Get the start
dt$start <- dt$end - dt$lengths + 1

# Select columns
dt <- dt[, c("number", "start", "end")]
# Sort rows
dt <- dt[order(dt$number), ]

dt
#  number start end
#2      0     3   4
#5      0     7   8
#1      1     1   2
#3      1     5   5
#4      2     6   6

更新

这里有一个使用with使代码更简洁的解决方案.

Update

Here is a solution using with to make the code more concise.

with(rle(a), data.frame(number = values,
                        start = cumsum(lengths) - lengths + 1,
                        end = cumsum(lengths))[order(values),])
#  number start end
#2      0     3   4
#5      0     7   8
#1      1     1   2
#3      1     5   5
#4      2     6   6

这篇关于获取值运行的开始和结束索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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