cumfuns | R Documentation |
cum_reset
will reset a cumulative function, FUN
, when
value
is encountered.
*_na
functions offer alternatives to the base
cumulative functions that can handle NA
s.
cum_mid
finds the mid-points between "stacked" numeric values.
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)
x |
a vector (or numeric matrix for |
value |
a value of |
FUN |
function to apply to each group, usually one of
|
useNA |
logical; if |
adj |
for |
A vector having the same length as x
with FUN
applied to
each group defined by positions of value
.
cumsum
; ave
; locf
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)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.