运行的开始和结束索引

运行的开始和结束索引

This question already has answers here:
Find start and end positions/indices of runs/consecutive values

(2个答案)


2年前关闭。




我有一个向量:
a <- c(1, 1, 0, 0, 1, 2, 0, 0)

我想获得每次运行的开始和结束索引相等的值:
number start  end
0        3     4
0        7     8
1        1     2
1        5     5
2        6     6

最佳答案

来自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使代码更简洁的解决方案。
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

关于r - 获取值运行的开始和结束索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46961415/

10-11 03:38