Menu
Coddy logo textTech

Map and mapply

Part of the Logic & Flow section of Coddy's R journey. Lesson 33 of 64.

Map(f, xs, ys) walks through two or more vectors in step and calls f with one element of each: first with the first elements, then with the second elements, and so on. It returns a list:

totals <- Map(function(q, p) q * p, c(2, 1, 3), c(4, 12, 2.5))
print(length(totals))
print(totals[[3]])

Output:

[1] 3
[1] 7.5

mapply() is the simplifying version, like sapply() for several vectors. unlist() also flattens the list from Map() into a vector:

print(mapply(function(q, p) q * p, c(2, 1, 3), c(4, 12, 2.5)))
print(unlist(Map(function(a, b) a + b, 1:3, 4:6)))

Output:

[1]  8.0 12.0  7.5
[1] 5 7 9

The vectors are matched by position, so they must have the same length. mapply() names text results after the first vector; USE.NAMES = FALSE removes the names:

items <- c("tea", "jam")
qty <- c(2, 3)
labels <- mapply(function(i, q) paste(q, "x", i), items, qty, USE.NAMES = FALSE)
print(labels)

Output:

[1] "2 x tea" "3 x jam"

When each pair needs an if, write a function with several arguments and pass it to mapply(). The condition then runs once per pair:

describe <- function(name, age) {
  group <- if (age < 18) "minor" else "adult"
  paste0(name, " (", group, ")")
}
print(mapply(describe, c("Ada", "Tim"), c(36, 12), USE.NAMES = FALSE))

Output:

[1] "Ada (adult)" "Tim (minor)"
challenge icon

Challenge

Easy

Complete order_lines(items, qty, prices). Return one line per item, 2 x tea = 8.00: the quantity, x , the item, = and the quantity times the price with two decimals. Use mapply() or Map().

The supplied code reads the items, the quantities and the prices as three comma-separated lines and prints each returned line.

Try it yourself

order_lines <- function(items, qty, prices) {
  # Write your code here
  character(0)
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(order_lines(strsplit(input[1], ",")[[1]], as.numeric(strsplit(input[2], ",")[[1]]), as.numeric(strsplit(input[3], ",")[[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