Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculating a rolling sum in R using the Reduce function
# Rolling sum using the Reduce function
EV <- c(1,.9,.8,.001,.001,.001,.001)
# Proportion of variance explained by each principle component.
prop_var <- EV / sum(EV)
# 0.3698224852 0.3328402367 0.2958579882
# 0.0003698225 0.0003698225 0.0003698225
# 0.0003698225
# Reduce is a higher order function. The first argument is a function that
# itself must take two arguments. The second argument is a vector.
Reduce(
function (x, y) { x + y },
prop_var,
accumulate = TRUE)
# 0.3698225 0.7026627 0.9985207 0.9988905
# 0.9992604 0.9996302 1.0000000
# Reduce takes the first element of the vector prop_var and calls the function
# with 0 and that first element, so 0 + 0.369, giving a result of 0.369. It then
# calls the function again with that result and the second element of the
# vector, meaning 0.369 + 0.333 = 0.70. It does the same thing for the third
# element of the vector, and so on until the end.
# If the accumulate = TRUE option is set, then the result is a vector containing
# all the intermediate values along with the final value.
# If accumulate = FALSE (the default), then it returns only the final value.
# This is where the name Reduce comes from, as it reduces a vector into a single
# value. The accumulate = TRUE variant is also known as the scan function in
# other programming languages.
# As such, Reduce abstracts the concept of turning a list of values into a
# single value by some kind of combining operation, which is this case is simply
# summation using +. If we used * then it'd be the product function. You can use
# any data type, such as joining the elements of a string vector from right to
# left:
Reduce(function (x, y) { paste(y, x) }, c("Cats", "are", "great"), right = TRUE)
# "great are Cats"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.