cumfuns: Cumulative functions

cumfunsR Documentation

Cumulative functions

Description

cum_reset will reset a cumulative function, FUN, when value is encountered.

*_na functions offer alternatives to the base cumulative functions that can handle NAs.

cum_mid finds the mid-points between "stacked" numeric values.

Usage

cum_reset(x, value = 0L, FUN)

cum_na(x, FUN, useNA = TRUE)

cumsum_na(x, useNA = TRUE)

cumprod_na(x, useNA = TRUE)

cummax_na(x, useNA = TRUE)

cummin_na(x, useNA = TRUE)

cum_mid(x, adj = 0.5)

Arguments

x

a vector (or numeric matrix for cum_mid)

value

a value of x which signals the end of a group and resets FUN

FUN

function to apply to each group, usually one of cumsum, cumprod, cummax, or cummin but can be any function that returns a vector the same length and type as the input (a la ave)

useNA

logical; if TRUE, indices with NA will be unchanged; if FALSE, the previous value is carried forward

adj

for cum_mid, an adjustment parameter, usually in [0, 1], giving the relative position between each value (default is centered, adj = 0.5)

Value

A vector having the same length as x with FUN applied to each group defined by positions of value.

See Also

cumsum; ave; locf

Examples

x <- 1:10
cum_reset(x, 5, cummin)
cum_reset(x, c(5, 8), cummin)

x[x %% 4 == 0] <- 0
cum_reset(x, FUN = cumsum)
cum_reset(x, FUN = sum)

set.seed(1)
x <- rpois(15, 1)
data.frame(
  x = x,
  y = cum_reset(x, FUN = cumsum),
  z = cum_reset(x, 0, function(x) ave(x, FUN = sum))
)

## x need not be numeric if FUN returns an appropriate type and length
cum_reset(letters[1:10], c('d', 'g'), function(x)
  letters[as.numeric(factor(x))])


## cum* functions to handle NA values
x <- 1:10
x[x %% 4 == 0] <- 0
na <- ifelse(x == 0, NA, x)

cumsum(x)
cum_na(x, cumsum)

cumsum(na)
cum_na(na, cumsum)

## shorthand
cumsum_na(na)
cumsum_na(na)


## like cum_reset, cum_na's FUN argument can be generalized if FUN
## returns the correct class and length of the input
FUN <- function(x) vector(class(x), length(x))
cum_na(na, FUN)

cumdiff <- function(x) Reduce(`-`, x, accumulate = TRUE)
cumdiff(x)
cumsum(c(x[1L], -x[-1L]))

cumdiff(na)
cumsum(c(na[1L], -na[-1L]))
cum_na(na, cumdiff)


## "stacked" numeric values, eg, from a barplot
set.seed(1)
x <- matrix(runif(12), ncol = 3L)
bp <- barplot(x, names.arg = paste('adj = ', c(0, 1, 0.5)))

for (ii in seq.int(ncol(x))) {
  xii <- x[, ii, drop = FALSE]
  text(bp[ii], cum_mid(xii, c(0, 1, 0.5)[ii]), xii, xpd = NA)
}


raredd/rawr documentation built on May 19, 2024, 1:02 p.m.