← Back to R Course | Chapter 11: Apply Family | Lesson 6 of 6

Reduce()

In this page:

  1. Reduce()

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()

markup
numbers <- c(1, 2, 3, 4, 5)

total <- Reduce("+", numbers)
cat("Total:", total, "\n")

running <- Reduce("+", numbers, accumulate = TRUE)
print(running)
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.