Menu
Coddy logo textTech

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] 15

Operators 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  40
challenge icon

Challenge

Easy

Complete 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")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler