Skip to contents

Returns the lengths and values of runs of consecutive equal elements in a vector.

Usage

rle2(x, order = FALSE, index = TRUE, na.last = TRUE)

Arguments

x

(Atomic vector)
The vector to be run length encoded.

order

(Scalar logical)
Whether or not to order the data frame based on the values in x.

index

(Scalar logical)
Whether or not to add the index position for each run/consecutive value in columns named 'start' and 'stop'.

na.last

(Scalar logical: TRUE)
Controls placement of NA runs when order = TRUE. TRUE puts them last, FALSE puts them first, NA drops them. Ignored when order = FALSE.

Value

data.frame with structure:

ColumnNameClassNote
1valueclass(x)
2lengthinteger
3startintegerOptional
4stopintegerOptional

Details

base::rle() returns a list with a custom print method. rle2() returns a data.frame, optionally annotated with the start and stop indices of each run, and optionally sorted by value.

Unlike base::rle(), consecutive NAs collapse into a single run. A transition between NA and a non-NA value also counts as a run boundary.

A zero-length x returns a zero-row data.frame with the documented columns.

The returned data.frame is not compatible with base::inverse.rle().

See also

Examples

#----------------------------------------------------------------------------
# rle2() examples
#----------------------------------------------------------------------------
library(bkbase)

x <- c(NA, NA, rev(rep(6:10, 1:5)), NA)

# base::rle() splits NAs into single-element runs and returns a list.
rle(x)
#> Run Length Encoding
#>   lengths: int [1:8] 1 1 5 4 3 2 1 1
#>   values : int [1:8] NA NA 10 9 8 7 6 NA

# rle2() collapses consecutive NAs and returns a data frame.
rle2(x)
#>   value length start stop
#> 1    NA      2     1    2
#> 2    10      5     3    7
#> 3     9      4     8   11
#> 4     8      3    12   14
#> 5     7      2    15   16
#> 6     6      1    17   17
#> 7    NA      1    18   18

# Drop the start and stop columns.
rle2(x, index = FALSE)
#>   value length
#> 1    NA      2
#> 2    10      5
#> 3     9      4
#> 4     8      3
#> 5     7      2
#> 6     6      1
#> 7    NA      1

# Sort by value. NA runs are placed last by default.
rle2(x, order = TRUE)
#>   value length start stop
#> 1     6      1    17   17
#> 2     7      2    15   16
#> 3     8      3    12   14
#> 4     9      4     8   11
#> 5    10      5     3    7
#> 6    NA      2     1    2
#> 7    NA      1    18   18

# Sort by value and drop NA runs entirely.
rle2(x, order = TRUE, na.last = NA)
#>   value length start stop
#> 1     6      1    17   17
#> 2     7      2    15   16
#> 3     8      3    12   14
#> 4     9      4     8   11
#> 5    10      5     3    7

# Works on any atomic vector, including character.
rle2(c("a", "a", "b", "a", "a", "a"))
#>   value length start stop
#> 1     a      2     1    2
#> 2     b      1     3    3
#> 3     a      3     4    6