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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With