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:
Syntax
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()
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
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
- Using
Reduceon an empty vector without aninitvalue, which returnsNULL. - Writing
Reduce(+, numbers)without quotes, which is a syntax error; use"+"or `+`. - Forgetting
accumulate = TRUEwhen you want the running results.
Chapter Summary
- The apply family applies a function across data without writing explicit loops.
apply(),lapply(),sapply(), andtapply()work on matrices, lists, and groups.Map()andReduce()combine or transform data with functions.