Reduce
Part of the Logic & Flow section of Coddy's R journey. Lesson 35 of 64.
Reduce(f, x) combines the elements of x into one value: it calls f on the first two elements, then on that result and the third element, and so on. With + it adds everything up:
print(Reduce(function(acc, x) acc + x, c(3, 5, 10)))
print(Reduce(`+`, 1:5))Output:
[1] 18
[1] 15Operators such as + are functions too. Written in backticks, `+` can be passed like any other function. Reduce() is most useful when there is no built-in function for the combination, such as keeping the longer of two words:
longer <- function(a, b) if (nchar(b) > nchar(a)) b else a
print(Reduce(longer, c("fig", "banana", "kiwi", "cherry")))Output:
[1] "banana"The third argument, init, is the starting value. It is used as the first acc, and it is also the result when x is empty:
print(Reduce(`+`, c(), 0))
print(Reduce(function(acc, w) paste0(acc, toupper(substr(w, 1, 1))), c("portable", "network", "graphics"), ""))Output:
[1] 0
[1] "PNG"accumulate = TRUE returns every intermediate result instead of only the last one, which gives running totals:
deposits <- c(100, -30, 50, -80)
print(Reduce(`+`, deposits, accumulate = TRUE))Output:
[1] 100 70 120 40Challenge
EasyComplete running_balance(start, changes). Starting from start, apply each change in order. Return one line per change with the balance after it, after 1: 70, and a last line lowest: followed by the lowest balance reached (including start).
The supplied code reads the start balance and the changes as a comma-separated line and prints each returned line.
Try it yourself
running_balance <- function(start, changes) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(running_balance(as.numeric(input[1]), as.numeric(strsplit(input[2], ",")[[1]])), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler