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

Reduce()

Reduce combines a list into one value by working step by step, like adding coins one at a time into a jar until you have a total. Each step uses the running result so far.

In this page:

  1. Reduce()
Syntax
r
Reduce(FUN, x)
Reduce(FUN, x, accumulate = TRUE)

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using Reduce on an empty vector without an init value, which returns NULL.
  2. Writing Reduce(+, numbers) without quotes, which is a syntax error; use "+" or ` + `.
  3. Forgetting accumulate = TRUE when you want the running results.
Chapter Summary
  • The apply family applies a function across data without writing explicit loops.
  • apply(), lapply(), sapply(), and tapply() work on matrices, lists, and groups.
  • Map() and Reduce() combine or transform data with functions.
🔒

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.