计算相同长度向量中的连续元素

时间:2019-01-07 10:18:30

标签: r vector count sequence run-length-encoding

如果我有像这样的向量

"a": 0 0 1 1 1 0 0 0 0 1 1 0 0 0

如何生成包含连续元素数的相同长度的向量,如下所示:

"b": 2 2 3 3 3 4 4 4 4 2 2 3 3 3

我尝试过rle,但是我没有设法以这种方式进行扩展。

3 个答案:

答案 0 :(得分:9)

另一个使用rlerep的选项

with(rle(a), rep(lengths, times = lengths))
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

数据

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

答案 1 :(得分:5)

使用diff创建分组变量,并在ave中使用它来计算每个组的length

ave(x, cumsum(c(0, diff(x) != 0)), FUN = length)
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

您可以对dplyr lag

做同样的事情
library(dplyr)       
ave(x,cumsum(x != lag(x, default = FALSE)), FUN = length)
#[1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

为了完整起见,data.table rleid

library(data.table)
ave(x, rleid(x), FUN = length)
#[1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

数据

x <- c(0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0)

答案 2 :(得分:1)

这是使用vapply

的另一种解决方案
count_consec <- function (a) {
  # creating output vector out
  out <- integer(length(a))

  # consecutive differences
  diffs <- which(diff(a) != 0)

  # returning 0 just in order to have a return statement in vapply - you can return anything else
  vapply(1:(length(diffs)+1), function (k) {
    if (k == 1) {
      out[1:diffs[1]] <<- diffs[1]
      return (0L)
    }
    if (k == length(diffs)+1) {
      out[(diffs[k-1]+1):length(out)] <<- length(out) - diffs[k-1]
      return (0L)
    }
    out[(diffs[k-1]+1):diffs[k]] <<- diffs[k] - diffs[k-1]
    return (0L)
  }, integer(1))
  out
}
count_consec(a)
# [1] 2 2 3 3 3 4 4 4 4 2 2 3 3 3

带有数据a <- as.integer(unlist(strsplit('0 0 1 1 1 0 0 0 0 1 1 0 0 0', ' ')))

相关问题