Skip to content

Instantly share code, notes, and snippets.

@mpettis
Created March 24, 2020 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpettis/1f50677fcc14d598c928818dad146260 to your computer and use it in GitHub Desktop.
Save mpettis/1f50677fcc14d598c928818dad146260 to your computer and use it in GitHub Desktop.
Run-length-encoding, making groups
## Using run-length-encoding, create groups of identical values and put that
## common grouping identifier into a `grp` column.
library(tidyverse)
set.seed(42)
df <- tibble(x = sample(c(0,1), size=20, replace=TRUE, prob = c(0.2, 0.8)))
df %>%
mutate(grp = rle(x)$lengths %>% {rep(seq(length(.)), .)})
#> # A tibble: 20 x 2
#> x grp
#> <dbl> <int>
#> 1 0 1
#> 2 0 1
#> 3 1 2
#> 4 0 3
#> 5 1 4
#> 6 1 4
#> 7 1 4
#> 8 1 4
#> 9 1 4
#> 10 1 4
#> 11 1 4
#> 12 1 4
#> 13 0 5
#> 14 1 6
#> 15 1 6
#> 16 0 7
#> 17 0 7
#> 18 1 8
#> 19 1 8
#> 20 1 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment