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

问题描述 投票:6回答:3

如果我有一个矢量

"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,但我没有设法以这种方式伸展它。

r vector count sequence run-length-encoding
3个回答
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)

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)

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', ' ')))

© www.soinside.com 2019 - 2024. All rights reserved.