Reduce()
In this page:
Reduce()
Reduce(FUN, x) combines all elements of a vector into a single value by repeatedly applying a binary function, like folding a list down with + to get a sum. Reduce("+", c(1,2,3,4)) computes ((1+2)+3)+4. Passing accumulate = TRUE returns every intermediate result instead of just the final one.
Note: Reduce("+", x) is a functional-programming alternative to sum(x), useful when the combining function isn't a simple built-in.
Example: Reduce()
numbers <- c(1, 2, 3, 4, 5)
total <- Reduce("+", numbers)
cat("Total:", total, "\n")
running <- Reduce("+", numbers, accumulate = TRUE)
print(running)
Login to try C/C++/Java/PHP code in the editor