Skip to content

Commit

Permalink
PR for tidyverse#446
Browse files Browse the repository at this point in the history
Implement tidyverse#446.
Maybe `.keep_names = TRUE` is a better default?
`.keep_names = FALSE` as default matches the original behaviour, but I can hardly imagine code relying on the fact that `accumulate(...)` is unnamed.
  • Loading branch information
AshesITR authored Feb 6, 2018
1 parent b6a0304 commit d16be5b
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions R/reduce.R
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ seq_len2 <- function(start, end) {
#' both functions keep the intermediate results.
#'
#' @inheritParams reduce
#' @param .keep_names If `TRUE`, names of `.x` will be copied to the result. Otherwise the result will be unnamed.
#' @export
#' @examples
#' 1:3 %>% accumulate(`+`)
Expand Down Expand Up @@ -170,25 +171,43 @@ seq_len2 <- function(start, end) {
#' geom_line(aes(color = simulation)) +
#' ggtitle("Simulations of a random walk with drift")
#' }
accumulate <- function(.x, .f, ..., .init) {
accumulate <- function(.x, .f, ..., .init, .keep_names = FALSE) {
.f <- as_mapper(.f, ...)

f <- function(x, y) {
.f(x, y, ...)
}

# Stop early so costly Reduce is called only when everything is fine
if (!is.logical(.keep_names) || length(.keep_names) != 1 || is.na(.keep_names)) {
rlang::abort("`.keep_names` must be TRUE or FALSE")
}

Reduce(f, .x, init = .init, accumulate = TRUE)
res <- Reduce(f, .x, init = .init, accumulate = TRUE)
if (.keep_names) {
names(res) <- names(.x)
}
res
}

#' @export
#' @rdname accumulate
accumulate_right <- function(.x, .f, ..., .init) {
accumulate_right <- function(.x, .f, ..., .init, .keep_names = FALSE) {
.f <- as_mapper(.f, ...)

# Note the order of arguments is switched
f <- function(x, y) {
.f(y, x, ...)
}

# Stop early so costly Reduce is called only when everything is fine
if (!is.logical(.keep_names) || length(.keep_names) != 1 || is.na(.keep_names)) {
rlang::abort("`.keep_names` must be TRUE or FALSE")
}

Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE)
res <- Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE)
if (.keep_names) {
names(res) <- names(.x)
}
res
}

0 comments on commit d16be5b

Please sign in to comment.