accumulate() : Accumulate intermediate results

reduce와 유사하지만 중간 단계를 다 유지한다
purrr
Author

chichead

Published

October 8, 2022

Today Function : reduce()

오늘의 함수는 purrr 패키지의 accumulate() 함수입니다. Two-Table Verbs 함수를 사용해서 3개 이상의 데이터테이블을 처리할 땐 reduce() 함수를 사용합니다. 그런데 그와 유사한 accumulate() 함수는 중간 단계를 모두 유지해줍니다.


Usage

accumulate(.x, .f, ..., .init, .dir = c("forward", "backward"))

accumulate2(.x, .y, .f, ..., .init)


Argument

.x : 리스트나 atomic vector가 들어갑니다
.f : accumulate() 함수에서는 Two-Table Verbs 함수가, accumulate2() 함수에는 그 이상의 함수를 사용할 수 있습니다.
.dir : accumulate의 방향을 정합니다.


Example

library(tidyverse)
library(purrr)

number <- sample(10)
number
 [1]  1  2  4  7  8  3 10  9  6  5
# reduce 함수로 다 더하면?
number |> reduce(`+`)
[1] 55
# accumulate는 각 단계를 유지해서 누적합을 계산합니다.
number |> accumulate(`+`)
 [1]  1  3  7 14 22 25 35 44 50 55