Created
March 24, 2020 15:41
-
-
Save mpettis/1f50677fcc14d598c928818dad146260 to your computer and use it in GitHub Desktop.
Run-length-encoding, making groups
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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