Learn R Programming

runner (version 0.3.0)

runner: Custom running function

Description

Applies custom function to running windows

Usage

runner(x, f, k = integer(1), lag = integer(1), idx = integer(0),
  na_pad = FALSE, type = "numeric")

Arguments

x

Vector of any type

f

function to be applied on x

k

integer vector or single value denoting size of the running window. If k is a single value then window size is constant for all elements, otherwise if length(k) == length(x) different window size for each element.

lag

integer vector or single value denoting window lag. If lag is a single value then window lag is constant for all elements, otherwise if length(lag) == length(x) different window size for each element. Negative value shifts window forward.

idx

date or integer an optional integer vector containing index of observation. If specified then k and lag are depending on idx. Length of idx should be equal of length x

na_pad

logical single value (default na_pad=FALSE) - if TRUE calculation on incomplete window will return NA. Incomplete window is when some parts of the window are out of range

type

output type ("logical", "numeric", "integer", "character")

Examples

Run this code
# NOT RUN {
runner(1:10, f = mean, k = 3)
runner(1:10, k = 3, f = function(x) mean(x, na.rm = TRUE))
runner(letters[1:10],
       k = c(1, 2, 2, 4, 5, 5, 5, 5, 5, 5),
       f = function(x) length(unique(x)))

runner(letters[1:10],
       k = c(1, 2, 2, 4, 5, 5, 5, 5, 5, 5),
       f = function(x) paste(x, collapse = "-"),
       type = "character")
# }

Run the code above in your browser using DataLab