roll_fun: Rolling functions

View source: R/utils.R

roll_funR Documentation

Rolling functions

Description

Apply rolling functions

Usage

roll_fun(x, n = 5L, FUN = mean, ..., fromLast = FALSE, keep = FALSE)

Arguments

x

a vector

n

size of groups

FUN

a function to apply as a name or literal character string

...

additional arguments passed to FUN

fromLast

logical; if TRUE, roll_fun is applied to x in reverse order

keep

logical; if TRUE, the rolling FUN is applied to the first n elements of x; if FALSE (default), then FUN is applied to x[1], x[1:2], ..., x[1:n], ie, until groups of size n are possible

Value

A vector of the same length of x with calculations obtained by FUN.

Examples

cbind(1:10, roll_fun(1:10, 2, keep = TRUE))
cbind(rep(1, 10), roll_fun(rep(1, 10), 5, sum))

dat <- data.frame(x = c(1, 1, 2, 2, 2, 3, 4, 5, 5, 5),
                  y = 1:10)
## compare:
within(dat,
  z <- unlist(by(dat, dat$x, function(ii)
          roll_fun(ii$y, length(ii$y), sum))))
do.call('rbind', by(dat, dat$x, cumsum))


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.