5

I read the manual for using accumulate saying that it is a 2-argument function. I don't understand the given example:

1:5 %>% accumulate(`+`)
#> [1]  1  3  6 10 15

If accumulate is a 2-argument function, should the first element that it outputs be 3? because 1+2=3, why can the first element can be the output?

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
tobinz
  • 305
  • 1
  • 7

2 Answers2

7

accumulate is a two argument function where the first argument is a vector and the second argument a function. Its output is also a vector of the same length as that of the input unless .init is supplied in which case it will be one length greater than the input length.

1:5 %>% accumulate(`+`)

#means

accumulate(1:5, `+`)

Now, accumulate calculates the output by rolling the supplied function between the individual elements of the supplied vector. Since the operation supplied as the second argument for the output requires two elements i.e. (i) output of previous element and (ii) next element, logically for the first time it may output the same element of the input vector without applying any operation.

1:5 %>% accumulate(`+`)
#> [1]  1  3  6 10 15

The case will be the same even if .init is provided and in that case the first element of the output vector will be equal to the supplied .init. (See Ronak's example)

library(purrr)
1:5 %>% accumulate(`+`, .init = 3)
#[1]  3  4  6  9 13 18

Now check that there are six elements in output vector despite five elements in input vector (1:5).

Your logic that the first element of the given output should be 3 is correct but in most cases the requirement of the output vector is of the same length as that of the input. Therefore, the developers may have thought to include the first element as such without any operation/application of function.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
4

.init argument decides which would be the 1st value in the output. If you haven't specified anything it returns the the first value of the vector as first value in the output (which is 1 here).

From ?accumulate.

.init - If supplied, will be used as the first value to start the accumulation, rather than using .x[[1]].

You can specify your own .init argument.

library(purrr)
1:5 %>% accumulate(`+`, .init = 3)
#[1]  3  4  6  9 13 18
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Does this answer the OP's question? It seems that the OP was asking "why the first element of the output is not 1+2=3", rather than "how to make the first element of the output 3". – mt1022 Feb 07 '21 at 05:16
  • 1
    @mt1022 I think it does. It is because of `.init` which is explained in 1st line of my answer along with relevant excerpt from the documentation. – Ronak Shah Feb 07 '21 at 05:40