run length encoding function not working

I would like to create a new column that identifies runs of "1s" and numbers greater than "1" from the variable A01.

run <- rle(as.character(ZIKV_red_tibble$A01>=2))
ZIKV_red_tibble$A01run<-sequence(run$lengths)

The resulting runs start over at the number "3".

Could you post an example data set and the resulting behavior of rle()? I cannot reproduce your problem.


set.seed(5389)
DF <- data.frame(A01 = sample(1:2, size = 20, replace = TRUE))
DF
#>    A01
#> 1    2
#> 2    1
#> 3    1
#> 4    1
#> 5    1
#> 6    1
#> 7    1
#> 8    1
#> 9    1
#> 10   1
#> 11   2
#> 12   1
#> 13   1
#> 14   1
#> 15   2
#> 16   2
#> 17   1
#> 18   2
#> 19   2
#> 20   2
run <- rle(as.character(DF$A01 >= 2))
run
#> Run Length Encoding
#>   lengths: int [1:7] 1 9 1 3 2 1 3
#>   values : chr [1:7] "TRUE" "FALSE" "TRUE" "FALSE" "TRUE" "FALSE" "TRUE"
DF$A01runs <- sequence(run$lengths)
DF
#>    A01 A01runs
#> 1    2       1
#> 2    1       1
#> 3    1       2
#> 4    1       3
#> 5    1       4
#> 6    1       5
#> 7    1       6
#> 8    1       7
#> 9    1       8
#> 10   1       9
#> 11   2       1
#> 12   1       1
#> 13   1       2
#> 14   1       3
#> 15   2       1
#> 16   2       2
#> 17   1       1
#> 18   2       1
#> 19   2       2
#> 20   2       3

Created on 2019-10-08 by the reprex package (v0.3.0.9000)

1 Like