Skip to content

Implement vec_identify_runs() and vec_rle() #1081

Description

@DavisVaughan

Inspired by the adjacency grouping idea in tidyverse/dplyr#5184

We could do much better than this in terms of performance with a C implementation. vec_group_rle() does a lot more work than is necessary here because it uses a dictionary to keep track of what it has already seen.

I've added this to the vec-prefixes google sheet

library(vctrs)
library(dplyr, warn.conflicts = FALSE)

vec_runs <- function(x) {
  rle <- vec_group_rle(x)
  lengths <- field(rle, "length")
  rep(seq_along(lengths), times = lengths)
}

mtcars <- as_tibble(mtcars)

mtcars %>%
  select(vs, am) %>%
  mutate(runs = vec_runs(across()))
#> # A tibble: 32 x 3
#>       vs    am  runs
#>    <dbl> <dbl> <int>
#>  1     0     1     1
#>  2     0     1     1
#>  3     1     1     2
#>  4     1     0     3
#>  5     0     0     4
#>  6     1     0     5
#>  7     0     0     6
#>  8     1     0     7
#>  9     1     0     7
#> 10     1     0     7
#> # … with 22 more rows

Created on 2020-05-05 by the reprex package (v0.3.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurea feature request or enhancement

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions