Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

cumall

Cumulativate versions of any, all, and mean


Description

dplyr provides cumall(), cumany(), and cummean() to complete R's set of cumulative functions.

Usage

cumall(x)

cumany(x)

cummean(x)

Arguments

x

For cumall() and cumany(), a logical vector; for cummean() an integer or numeric vector.

Value

A vector the same length as x.

Cumulative logical functions

These are particularly useful in conjunction with filter():

  • cumall(x): all cases until the first FALSE.

  • cumall(!x): all cases until the first TRUE.

  • cumany(x): all cases after the first TRUE.

  • cumany(!x): all cases after the first FALSE.

Examples

# `cummean()` returns a numeric/integer vector of the same length
# as the input vector.
x <- c(1, 3, 5, 2, 2)
cummean(x)
cumsum(x) / seq_along(x)

# `cumall()` and `cumany()` return logicals
cumall(x < 5)
cumany(x == 3)

# `cumall()` vs. `cumany()`
df <- data.frame(
  date = as.Date("2020-01-01") + 0:6,
  balance = c(100, 50, 25, -25, -50, 30, 120)
)
# all rows after first overdraft
df %>% filter(cumany(balance < 0))
# all rows until first overdraft
df %>% filter(cumall(!(balance < 0)))

dplyr

A Grammar of Data Manipulation

v1.0.6
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre] (<https://orcid.org/0000-0003-4757-117X>), Romain François [aut] (<https://orcid.org/0000-0002-2444-4226>), Lionel Henry [aut], Kirill Müller [aut] (<https://orcid.org/0000-0002-1416-3412>), RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.