Chuliang Xiao
Chuliang Xiao

Reputation: 359

Iteration with purrr::reduce()

Given a function f(a, x) = a*x with an initial a = 3, suppose to have an iteration where a is assigned with f(a, x) in the next step.

How to use purrr to realize the iteration? The following is not quite right.

library(purrr)
a <- 3
f <- function(a, x) a*x

2:4 %>% reduce(~f(a, .))
#> [1] 18

2:4 %>% accumulate(~f(a, .))
#> [1]  2  6 18

Created on 2020-04-24 by the reprex package (v0.3.0)

Upvotes: 2

Views: 626

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

In base R, you can use Reduce with accumulate = TRUE.

Reduce(f, 2:4, init = 3, accumulate = TRUE)
#[1]  3  6 18 72

Upvotes: 2

MrFlick
MrFlick

Reputation: 206167

Here you seem to be after

2:4 %>% accumulate(~f(.y, .x), .init=3)
# [1]  3  6 18 72

The .x value represents your previous value and the .y here is the next elements from the vector you are piping in. Rather than hard coding the a=3 in the function, we pass that in via .init= to it only occurs on the first iteration.

Upvotes: 1

Related Questions