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)
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
Created on 2020-05-05 by the reprex package (v0.3.0)