Calculates running series of consecutive elements

streak_run(
  x,
  k = integer(0),
  lag = integer(1),
  idx = integer(0),
  at = integer(0),
  na_rm = TRUE,
  na_pad = FALSE
)

Arguments

x

any type vector which running function is calculated on

k

(integer or character)
Window size. Single value or vector of length(x). Omit for cumulative windows. Accepts time-interval strings (e.g. "5 days") when idx is set.

lag

(integer or character)
Window shift. Positive shifts back, negative shifts forward. Single value or vector of length(x). Accepts time-interval strings when idx is set.

idx

(integer, Date, POSIXt)
Sorted index of observations. When set, k and lag refer to index distance rather than element count. Must be same length as x.

at

(integer, Date, POSIXt, character)
Indices at which to evaluate windows. Output length equals length(at) instead of length(x). A single time-interval string (e.g. "month") generates a regular sequence over the range of idx.

na_rm

logical single value (default na_rm = TRUE) - if TRUE sum is calculating excluding NA.

na_pad

(logical)
If TRUE, return NA for windows that extend beyond the data range.

Value

streak numeric vector of length equals length of x containing number of consecutive occurrences.

Examples

set.seed(11)
x1 <- sample(c("a","b"), 15, replace = TRUE)
x2 <- sample(c(NA_character_, "a", "b"), 15, replace = TRUE)
k <- sample(1:4, 15, replace = TRUE)
streak_run(x1) # simple streak run
#>  [1] 1 2 3 1 1 1 2 1 2 3 1 1 2 3 1
streak_run(x1, k = 2) # streak run within 2-element window
#>  [1] 1 2 2 1 1 1 2 1 2 2 1 1 2 2 1
streak_run(x2, na_pad = TRUE, k = 3) # streak run within k=3 with padding NA
#>  [1] NA NA  1  1  2  2  2  1  1  1  2  3  1  2  1
streak_run(x1, k = k) # streak run within varying window size specified by vector k
#>  [1] 1 2 2 1 1 1 2 1 2 2 1 1 1 3 1